Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Introduction to Perl 5.10 for Unix System Administrators

(Perl 5.10 without excessive complexity)

by Dr Nikolai Bezroukov

Contents : Foreword : Ch01 : Ch02 : Ch03 : Ch04 : Ch05 : Ch06 : Ch07 : Ch08 :


Prev | Up | Contents | Down | Next

Advanced Subroutine Techniques


Subroutine Prototypes

Perl 5.002 introduces the capability to declare limited forms of subroutine prototypes. This capability allows early detection of errors in the number and type of parameters and generation of suitable warnings. This is primarily to allow the declaration of replacement subroutines for built-in commands. To use the stricter parameter checking, however, you must make the subroutine call by using only the subroutine name (without the & prefix). The prototype declaration syntax is concise and not as strict as the named formal parameters mechanism is in languages such as Pascal.

The main use for these prototypes at present is in writing modules for wider use, allowing the modules to specify their parameter types so as to trap errors and print diagnostic messages.

Subroutine Recursion

One the most powerful features of subroutines is their capability to call themselves. Many problems can be solved by repeated application of the same procedure. You must take care to set up a termination condition wherein the recursion stops and the execution can unravel itself. Typical examples of this approach occur in list processing: Process the head item and then process the tail; if the tail is empty, do not recurse. Another neat example is the calculation of a factorial value, as follows:

How to Return Arrays from a Subroutine

Subroutines can also return values, thus acting as functions. The return value is the value of the last statement executed; it can be a scalar or an array value. You can test whether the calling context requires an array or a scalar value by using the wantarray construct, thus returning different values depending on the required context. The following example, as the last line of a subroutine, would return the array (a,b,c) in an array context and the scalar value 0 in a scalar context:

wantarray ? (a, b, c) : 0;

You can return from a subroutine before the last statement by using the return() function. The argument to the return function is the returned value, in this case. The use of return() is illustrated in the following example (which is not a very efficient way to do the test but illustrates the point):

When multiple arrays are returned, the result is flattened into one list so that effectively, only one array is returned.

Imitating named arguments using hashes

Perl subroutines, by default, use "positional arguments." This means that the arguments to the subroutine must provided in pre-defined order to be correctly processed as parameters. For subroutines with a small argument list (three or fewer items), this isn't a problem.

sub pretty_print {
    my ($filename, $text, $text_width) = @_;

    # Format $text to $text_width somehow.

    open my $fh, '>', $filename
        or die "Cannot open '$filename' for writing: $!\n";

    print $fh $text;

    close $fh;

    return;
}

pretty_print( 'filename', $long_text, 80 );

Named Parameters in Perl

However, once everyone starts using your subroutine, it starts expanding what it can do. Argument lists tend to expand, making it harder and harder to remember the order of arguments.

sub pretty_print {
    my (
        $filename, $text, $text_width, $justification, $indent,
        $sentence_lead
    ) = @_;

    # Format $text to $text_width somehow. If $justification is set, justify
    # appropriately. If $indent is set, indent the first line by one tab. If
    # $sentence_lead is set, make sure all sentences start with two spaces.

    open my $fh, '>', $filename
        or die "Cannot open '$filename' for writing: $!\n";

    print $fh $text;

    close $fh;

    return;
}

pretty_print( 'filename', $long_text, 80, 'full', undef, 1 );

Quick question: What does the last parameter equal to one means? If it can't instantly answer this question the number of parameters is two big to pass them positionally and you need to figure a better way.

The most maintainable solution is to use "named arguments." In Perl 5, the best way to implement this is by using a hash reference that will be discussed in datil in the next chapter. Here we just mention that how to pass a hash reference:

sub pretty_print {
    my $ref = shift; # we got a reference into local variable href

    # Format $ref->{text} to $ref->{text_width} somehow.
    # If $ref->{justification} is set, justify appropriately.
    # If $ref->{indent} is set, indent the first line by one tab.
    # If $ref->{sentence_lead} is set, make sure all sentences start with
    # two spaces.

    open my $fh, '>', $ref->{filename}
        or die "Cannot open '$ref->{filename}' for writing: $!\n";

    print $fh $ref->{text};

    close $fh;

    return;
}

pretty_print((filename      => 'filename',
    text          => $long_text,
    text_width    => 80,
    justification => 'full',
    sentence_lead => 1,
));

Now, the reader can immediately see exactly what the call to pretty_print() is doing.

Optional Arguments

By using named arguments, you gain the benefit that some or all of your arguments can be optional without forcing our users to put undef  in all of the positions they don't want to specify.

A more complex example of function

A common Perl task is split a line according to some rules. That usually should be done with every line and subroutine is a natural solution here. For example Unix /etc/passwd file has a structure:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:
daemon:x:2:2:daemon:/sbin:
adm:x:3:4:adm:/var/adm:
lp:x:4:7:lp:/var/spool/lpd:
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:
news:x:9:13:news:/var/spool/news:
uucp:x:10:14:uucp:/var/spool/uucp:
operator:x:11:0:operator:/root:
games:x:12:100:games:/usr/games:
gopher:x:13:30:gopher:/usr/lib/gopher-data:
ftp:x:14:50:FTP User:/home/ftp:
nobody:x:99:99:Nobody:/:
postgres:x:100:100:PostgreSQL Server:/var/lib/pgsql:/bin/bash
xfs:x:101:101:X Font Server:/etc/X11/fs:/bin/false
bezroun:x:501:501:Nikolai Bezroukov:/home/bezroun:/bin/bash

If we need to get the first field (login name) and the last field (shell) from all records, we can write the following subroutine:

while(<>) {
  chomp($_);
  $user_shell=getusershell($_);
  print "user $user_shell\n;
}
sub getusershell { 
my @w;  
   @w = split(/:/,$_[1]);
   return ($w[0].': '.$w[-1]);
}

From the example above it's clear that call subroutine one needs to specify its name and the list of parameters, if any:

 $user_shell=getusershell($_);

The last value evaluated in subroutine is the value returns by default

In Perl subroutines, the last value seen by the subroutine becomes the subroutine's return value. In the example above, the return value is provided explicitly in return statement, but it can be rewritten as:

sub getusershell 
{ 
my @w, arg; 
   @w = split(/:/,$_[1]); 
   $arg=$w[0].' '.$w[-1]; # the value of $arg will be returned 
                          # as if statement return $arg was present
}

That's not a good practice to rely on this mechanism and it is better always use explicit return statement.

Recommended Links

Advanced Subroutine Techniques - Perl.com

Subroutines-in-Perl



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March, 12, 2019