- Perl ›
- builtin functions ›
- here
return function - return return value
You can use the return function to return the return value of a subroutine.
return Return value
When actually using it, write return in the subroutine.
sub sum { my ($num1, $num2) = @_; my $total = $num1 + $num2; # Return of return value return $total; }
The return value can be obtained by calling the subroutine.
my $return_value = sum (2, 4);
Empty return
An empty return has a special syntax, list context, an empty list, scalar context, undef is returned.
# Empty return return
Empty returns are a frequently used syntax in Perl.
Multiple return values
In Perl, using list or array will return multiple values. I can.
# Return list return(3, 5); # Return array my @nums = (3, 5); return @nums;
You can return multiple values this way, but I personally prefer to return an array reference rather than an array.
What is the difference between return and exit?
While return is used to return to the caller from within a subroutine, exit terminates the program itself. Be sure to use return when you finish the subroutine. It is rare to explicitly describe exit.
Learn more about how to use return
For details on how to create a subroutine, see the following article. It also explains in detail how to use return.