Google

Lesson two part 2

Lesson two part 2

Contact:[email protected]

Subroutines:

As soon as you start doing things more than once in any computer language,
it's usually a good idea to create a subroutine to take care of these
things. Let's say that you are reading numbers in and computing the square
of each number. It would be handy to have a subroutine to take care of that,
so consider the following example:

#!/usr/bin/perl

print "enter a list of numbers. (control-c to quit)\n";

while (<>) {
  chomp;
  $result = square ( $_ );
  print "the square of $_ is $result.\n";
}

sub square {
  my ( $number ) = @_;
  $number = $number * $number;
  return ( $number );
}

Whoa there! What happened to all the variable names? Well, in Perl there is
a default variable (referred to as $_) that is implied wherever there would
normally be a variable. Standard input from the keyboard is also implied
when we do the while (<>) statement. In this case, what we are actually
saying is something like this: while ( $_ = ) meaning that we are setting
the default variable to whatever is typed in, one line at a time.

The next line sets the variable $result to be equal to the output of the
subroutine square ( ). We are sending $_, or whatever the user typed in, to
the subroutine square ( ) as a parameter. With luck, square ( ) will return
the square of $_, so in the next line we print out the result.

The subroutine is defined at the bottom. In fact, it doesn't matter where
you define a subroutine! Let's take a look at the first line in the
subroutine "my ( $number ) = @_;" The special array variable @_ holds an
array of the parameters that were sent to this subroutine. Because it is an
array, we have to list our variables in an array form, which is why we have
parentheses around $number. But, because we may have used the variable
$number somewhere else in this script, we want to confine the scope of
$number to just this subroutine, so we don't clobber whatever values may
already have been in there (that's what the "my" does). Next, we compute the
square of $number, and lastly we return the result. Now we have a routine,
that we can call over and over with different values, that computes the
square.


Back to the Index