Like HowStuffWorks on Facebook!

How Perl Works


You create a subroutine with the word sub. All variables passed to the subroutine arrive in an array called _. Therefore, the following code works:

   show ('cat', 'dog', 'eel');

   sub show
      for ($i = 0; $i <= $#_; $i++)
         print $_[$i], "\n";

Remember that $# returns the highest index in the array (the number of elements minus 1), so $#_ is the number of parameters minus 1. If you like that sort of obtuseness, then you will love PERL.

You can declare local variables in a subroutine with the word local, as in:

   sub xxx
      local ($a, $b, $c)

You can also call a function using &, as in:

&show ('a', 'b', 'c');

The & symbol is required only when there is ambiguity, but some programmers use it all the time.

To return a value from a subroutine, use the keyword return.

More to Explore