Lesson 23: Subroutines or Custom functions


Is there a block of code that you use more than once in your script? If so you should write a subroutine.

  • A subroutine is a custom function
  • Allows you to reduce the chances of introducing an error into repetitive blocks of code
  • If you decide to change your block of code, you only have to change it in one place
  • Simplifies the flow of your script. Now you have a useful function name instead of many lines of code
  • You can pass arguments to the subroutine
  • You can have your subroutine return values

To make a subroutine

  1. place the subroutine below the place you want to use the function
  2. use the function sub
  3. give it an informative name.
  4. arguments come in on a special array called '@_' or the magic carpet array. It is very similar to @ARGV.
  5. use the return function to return values.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
my $answer = doSomeMath (3 , 4 , 6);
print "the answer is $answer\n";
 
##subroutines
sub doSomeMath {
  my @numbers = @_;
  my $sum;
  foreach my $num (@numbers){
    ## adding $num to the previous value of $sum
    $sum += $num;
  }
  my $product = $sum * 2;
  foreach my $num (@numbers){
    ## multiplying each $num to the previous value of $product
    $product *= $num;
  }
  return $product;
}

Output:

%% perl sub.pl
the answer is 1872

Note:

  • Arrays can be passed into and out of a subroutine, but if more than one is passed in or out, the contents will be merged into one list.
  • Hashes are lists of key/value pairs so they can also be passed into and out of a subroutine.
  • More complicated datastructures do not get pass around nicely unless you pass just a reference to the subroutine.
  • Exercises

    1. Create a factorial subroutine that takes one number as an argument calculates the factorial of that number and then returns the one result

    Print Friendly

    Leave a Reply

    Your email address will not be published. Required fields are marked *