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:

  1. We define a subroutine vals() that returns a list of two integers.

  2. In the main part of the script, we use list assignment to capture both return values from vals().

  3. We then print these values.

  4. 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.