First ... Back ... Next ... Last ... (Notes home)

Subroutines

  • Note that Perl does not distinguish between subroutines and functions. Methods are about the same, too, though in the Object Oriented (OO) context.
  • Subroutines may be called in many different ways. The easiest, and most consistent with other languages, is to define them (along with argument lists), then call them as needed. Generally, subroutines should be defined before used.
  • See Programming Perl pp. 220-221 for concise examples of prototypes and varieties, including how to treat Perl's pass by reference into pass by value.
  • The special variable @_ contains the list of arguments in LIST context (that it, it will flatten arrays). Pass a reference if either your arguments are long or if you need to get arrays or other types intact.
  • Prototype prototypes might be beneficial, but can also cause some errors if improperly used. Decide whether or not to use a prototype for a given prototype.
  • Prototype examples
    # Declare before use:
    sub newsub;
    # Use:
    newsub(2);
    # Define:
    sub newsub() {
      my $x=shift(@_);
      print "You passed me a value of " . $x . "\n";
    }
    
    # Declare:
    sub submarine(\$);
    my $q=10;
    print "q=$q\n";
    $ Use:
    submarine($q);
    print "q=$q\n";
    # Define:
    sub submarine(\$) {
     my $r=shift(@_); # assign reference to local variable
     $$r += 10;       # modify what's pointed to, not a local
    }
    

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby