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


Returning variables

Variables may be returned from a subroutine, and subsequently captured in the main program, by having a return VARIABLE_LIST; line within the routine. For example,
  my ($x, $y) = (3, 4);
  my $z = times_them($x, $y);
  print qq{$x times $y is $z\n};

  sub times_them {
    my ($a, $b) = @_;
    my $c = $a * $b;
    return $c;
  }
You can return, and subsequently capture within the calling program, multiple variables by specifying them in a list:
  my ($x, $y) = (3, 4);
  my ($u, $v) = times_and_add_them($x, $y);
  print qq{$x times $y is $u, and $x plus $y is $v\n};

  sub times_and_add_them {
    my ($a, $b) = @_;
    my $c = $a * $b;
    my $d = $a + $b;
    return ($c, $d);
  }
It is not necessary to only return at the end of a subroutine; sometimes, it is more natural to return at an earlier stage:
  my ($x, $y) = (3, 4);
  if (my $z = divide_them($x, $y)) {
    print qq{$x divided by $y is $z\n};
  }
  else {
    print qq{$x divided by $y is infinite\n};
  }

  sub divide_them {
    my ($a, $b) = @_;
    if ($b == 0) {
      return undef;
    }
    else {
      my $c = $a / $b;
      return $c;
    }
  }
However, you should generally ensure that all branches of your subroutine will return something. The above also illustrates the use of the return value of a subroutine in a conditional - if in the above $b was zero, the subroutine will return an undefined value, and a friendly message printed out (if this check was not done, and $b was zero, the program would die with a nasty error message about trying to divide something by zero).