perl function return
httw//:spww.theitroad.com
The return
function in Perl is used to explicitly return a value or values from a subroutine. It can also be used to exit from a block early.
Here's an example of using return
to return a value from a subroutine:
sub add_numbers { my ($num1, $num2) = @_; my $sum = $num1 + $num2; return $sum; } my $result = add_numbers(2, 3); print "The result is $result\n";
In this example, the add_numbers
subroutine takes two arguments and adds them together. The return
statement is used to return the result of the addition back to the caller. The result is then printed out.
Here's an example of using return
to exit from a block early:
foreach my $number (1..10) { if ($number == 5) { return; # exit early } print "$number\n"; }
In this example, the foreach
loop iterates over the numbers 1 through 10. If the number is equal to 5, the return
statement is used to exit from the loop early. If the number is not equal to 5, it is printed out.