Lecture#4 Outline


Chapter 4 - Subroutines

As a general rule, you define subroutines at the top of the file

sub sub_name {
   print "You're in the subroutine!\n";
}


Calling a subroutine:

&sub_name;

Always use the &. You don't need it if you're sure that your subroutine doesn't have the same name as a built in function, but better safe than sorry.

The return value of a function is the result of the last thing evaluated, so for example, in the last example the return value if the result of the print statement...probably a 1.


sub mysub {
   print "Hey there!\n";
   $n;
}
The value of $n is returned...normally though, we'll put in the return statement even though it's not necessary:


sub mysub {
   print "Hey there!\n";
   return $n;  #Returning a global
}
Subroutines can return pretty much anything you want them to.


Arguments

Just enclose them in parentheses....

&mysub(10, $a);

The parameters are passed into the default array @_ (by reference if possible), which is local to the subroutine


sub max {
   if ($_[0] > $_[1])  {
      return $_[0];    #This ; is optional
   }
   else {
      return $_[1];    #This ; is optional
   }
}
As you can see, you could call a subroutine with the wrong number of parameters! You would need to check the number passed in or implement a foreach loop....


sub add {
   print "We have ", scalar @_, " variables\n";
   my $sum=0;
   foreach (@_) {
      $sum+=$_;
   }
  return $sum;
}


Local Variables

sub mysub {
   my ($a, $b) = @_;  #$a gets $_[0], $b gets $_[1]
   return $a;
}
$a no longer exists after the subroutine is over


sub mysub {
   local ($a, $b) = @_;  #$a gets $_[0], $b gets $_[1]
   return $a;
}
same effect, but $a and $b's values are 'global' until the subroutine is over. This example shows the difference better:


$temp = "global";
&one();  #()s aren't necessary
&two();
&three;

sub one {print "$temp";}
sub two {local ($temp) = "local"; &one();}
sub three {my($temp) = "my"; &one();}

The call to one would print "global"
The call to two would print "local" - $temp declared in the subroutine is global until that subroutine is over.
The call to three would print "global" - scope of my is only the current block


The use strict pragma

At the top of your programs, after the include directive.

#!/usr/local/bin/perl

use strict;

Stops you from making as many mistakes by forcing you to use some good programming practices.
One minor nusance: All variables (in subroutines) must be declared with my.


CSC255 - Alan Watkins - North Carolina State University