Multiple Return Values in Perl
Perl has support for returning multiple values from subroutines, which is similar to the multiple return values feature in some other languages. This feature is often used in Perl to return both result and error values from a subroutine.
use strict;
use warnings;
# The subroutine 'vals' returns a list of two integers
sub vals {
return (3, 7);
}
# In the main part of the script
my ($a, $b) = vals();
print "$a\n";
print "$b\n";
# If you only want a subset of the returned values,
# you can use the scalar context or ignore some values
my $c = (vals())[1]; # Gets the second value
print "$c\n";
In this Perl script:
We define a subroutine
vals()
that returns a list of two integers.In the main part of the script, we use list assignment to capture both return values from
vals()
.We then print these values.
If you only want a subset of the returned values, you can use the scalar context or ignore some values. In this example, we’re getting just the second value from
vals()
.
To run the script:
$ perl multiple_return_values.pl
3
7
7
Perl’s ability to return and handle multiple values from subroutines provides flexibility in function design and usage, similar to multiple return values in other languages.
Perl also supports variable arguments in subroutines, which we’ll explore in the next example.