subroutines intermediate

How to return multiple values from a subroutine in Perl?

Question

How to return multiple values from a subroutine in Perl?

Perl subroutines can return multiple values by returning a list, which can then be captured in various ways depending on your needs. This flexibility is one of Perl's strengths, allowing you to handle return values in list context, scalar context, or by unpacking into individual variables.

The most common approach is to simply return multiple values separated by commas. Perl automatically creates a list from these values, and the caller can assign them to multiple variables or capture them as an array or array reference.

#!/usr/bin/perl
use strict;
use warnings;

# Subroutine returning multiple values
sub get_user_info {
    my $name = "Alice";
    my $age = 30;
    my $city = "New York";
    
    return ($name, $age, $city);  # Return list
}

# Method 1: Capture in separate variables
my ($user_name, $user_age, $user_city) = get_user_info();
print "Method 1: $user_name, $user_age, $user_city\n";

# Method 2: Capture in an array
my @user_data = get_user_info();
print "Method 2: ", join(", ", @user_data), "\n";

# Method 3: Capture only what you need
my ($name_only, undef, $city_only) = get_user_info();
print "Method 3: $name_only lives in $city_only\n";

# Method 4: Scalar context returns the last value
my $scalar_result = get_user_info();
print "Method 4 (scalar context): $scalar_result\n";

# Returning a hash for named access
sub get_person_details {
    return (
        name => "Bob",
        age => 25,
        occupation => "Engineer"
    );
}

my %person = get_person_details();
print "Hash return: $person{name} is a $person{occupation}\n";

Key Concepts and Gotchas

  • Context matters: In scalar context, a list return evaluates to the last element. Use wantarray to detect context if you need different behavior.
  • Parentheses are optional: return $a, $b, $c; works the same as return ($a, $b, $c);, but parentheses improve readability.
  • Unpacking with undef: Use undef in list assignments to skip unwanted return values.
  • Hash returns: Returning key-value pairs that can be assigned to a hash is idiomatic for named returns, especially when you have many values.
  • Array references: For large datasets, consider returning an array reference (return \@array;) for efficiency, though this changes the calling convention.

Remember that Perl flattens lists, so returning nested structures requires references. Always use strict and warnings to catch common mistakes with return values.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Method 1: Alice, 30, New York
Method 2: Alice, 30, New York
Method 3: Alice lives in New York
Method 4 (scalar context): New York
Hash return: Bob is a Engineer
STDERR
(empty)

Was this helpful?

Related Questions