Mike Gossland's Perl Tutorial Course for Windows

Introduction | String Functions | Array Functions | Test Functions | User Functions

Chapter 3. Functions

User Functions

Using the built-in functions of Perl will take you a long way. But eventually you'll have a repetitive chore that you want to call from more than one place in your program. You separate the block of code you want to perform into a function and call it whenever you need it.

Suppose you wanted to make a geometric mean function, where you take two numbers, multiply them and return the square root. Here's how it would look:


print "The geometric mean of $x and $y is: ", geomean($x, $y), "\n";

sub geomean() {
  ($a, $b) = @_;
  return sqrt( $a*$b );

A couple of interesting points. First, the function is declared with the use of the word "sub", meaning subroutine. Subroutines and functions are synonymous here.

The other interesting thing here is that the parameters $x and $y are passed to the function inside parentheses. But in the place where the function is defined, in the sub geomean() line, there's no mention of input parameters.

Instead, on the line:  ($a, $b) = @_; we see this strange @_ thing. What's that? Hm. It's the "default array" — the parameter list, passed in as an array, with the default name @_. It's very similar to the default variable $_, but it's an array instead of a scalar!

The line ($a, $b) = @_; is a list assignment. It assigns what was passed in as $x and $y to $a and $b, respectively.

The rest of the function is easy. It just returns the square root of the product, like it should.

In practice you'll see many different ways of retrieving the values from the default array. Sometimes you'll see a list assignment as above, and sometimes a series of "shift" statements instead. We could have written:

sub geomean() {
  $b = shift;
  return sqrt( $a*$b);

because if no array is provided to the shift function, it operates on the default array!

That ends the brief introduction to functions in Perl. With this chapter behind you, you've got ammunition to tackle some pretty advanced Perl jobs. Now let's see how to read and write results to files in the next chapter.