next up previous contents index
Next: Modules Up: Subroutines, functions, and modules Previous: Passing in and returning   Contents   Index


References to subroutines

Fairly often one comes across a situation where, depending on the truth of some condition, one wants to call one routine or another. This can be done striaghtforwardly as
  my $x = int(rand 2211);
  if ($x % 2 == 0) {
    print_is_even($x);
  }
  else {
    print_is_odd($x);
  }

  sub print_is_even {
    my $n = shift;
    print qq{$n is even\n};
  }
  sub print_is_odd {
    my $n = shift;
    print qq{$n is odd\n};
  }
However, it can also be done using a reference to a subroutine:
  my $x = int(rand 2211);
  my $subref = ($x % 2 == 0) ? \&print_is_even : \&print_is_odd;
  $subref->($x);

  sub print_is_even {
    my $n = shift;
    print qq{$n is even\n};
  }
  sub print_is_odd {
    my $n = shift;
    print qq{$n is odd\n};
  }
Note the use of the & symbol in constructing the subroutine reference - this is needed so that Perl interprets the name that follows as a subroutine, and not an ordinary string.

References to subroutines can be treated just like references to other types of variables - for example, they can be passed into subroutines as arguments, and they can be used as values for a hash in a complex data structure. With all of these types of references floating around, sometimes it would be useful to find out just what kind of reference a given variable is; for this, you can use the ref($variable) function, which will return SCALAR, ARRAY, HASH, or CODE for, respectively, a reference to a scalar, array, hash, or subroutine.


next up previous contents index
Next: Modules Up: Subroutines, functions, and modules Previous: Passing in and returning   Contents   Index