Perlaccess : Tutorials : Subroutines
Feeding Subroutines (5.2)
by Jacob A. Wheeler
http://www.bigresources.com

Now I am going to show you some more advanced ways of working with subroutines. Below are a few examples on passing variables through subroutine calls. These really come in handy when creating error handling routines.

  1. &getIP;
  2. &display;($IP);
  3. sub GetIP {
  4. $IP = $ENV{'REMOTE_ADDR'};
  5. }
  6. sub display {
  7. print "Your IP Address: @_\n";
  8. }

The following will do the same thing:

  1. &getIP;
  2. &display;($IP);
  3. sub GetIP {
  4. $IP = $ENV{'REMOTE_ADDR'};
  5. }
  6. sub display {
  7. local($i) = @_;
  8. print "Your IP Address: $i\n";
  9. }

Here is an example of where it would come in handy for passing error messages.

  1. open(FILE,"file.txt") || &error;("Error:" $file);;
  2. @file = <FILE>;
  3. close(FILE);

    Now lets pretend file.txt does not exist, thus it can't be opened! The code, || = Or. So perl will try opening the file, OR it will execute the error subroutine if the file is not found.

  4. sub error {
  5. local($error) = @_;
  6. print "$error\n";
  7. }