10

How do I return multiple values from a Perl function call?

Sample code

my ($value1, $value2, $value3) = getValues(@parts)

sub getValues
{
    foreach(@_)
    {
        $_ =~ m{/test1_name (.*) test2_name (.*) test3_name (.*)/};

        $test1_value = $1;
        $test2_value = $2;
        $test3_value = $3;
    }
}

This code is not working.

2
  • Could you show how your array @parts is being declared? Commented Sep 9, 2011 at 21:10
  • Just to make sure you're aware, I only took the first value from your array @parts. If you would like to do this for all of the values in this array, then you'll have to use a for loop. Commented Sep 9, 2011 at 21:35

3 Answers 3

24
my ($value1, $value2, $value3) = getValues(shift @parts);

sub getValues
{
   my $str = shift @_;

   $str =~ m{/test1_name (.*) test2_name (.*) test3_name (.*)/};

   return ($1, $2, $3);
}

You don't need to put it in the foreach loop if you're just trying to get $1, $2, $3. The my $str = shift @_; basically says "set the variable str to the first item in the values passed into this sub".

Also, you're passing in an array. I did a shift because that takes the first value from the array (which I'm assuming is the string you would like to parse). If you're trying to do something different, update your question and I'll update my answer.

Sign up to request clarification or add additional context in comments.

Comments

9

In addition to the other answers given, you can take advantage of the fact that a regular expression match in list context returns the capturing parenthesis, and that all subroutines return their last evaluated expression:

my ($value1, $value2, $value3) = getValues($parts[0]);

sub getValues {
    shift =~ m{/test1_name (.*) test2_name (.*) test3_name (.*)/}
}

Since that subroutine is so simple, you could also write it this way:

my $getValues = qr{/test1_name (.*) test2_name (.*) test3_name (.*)/};

my ($value1, $value2, $value3) = $parts[0] =~ $getValues;

Comments

2

The Perl idiom would be to return the multiple values in a list and then assign the result of the function to the list of variables that you want to receive values. You've already assigned the result of the function correctly, so the only change you need is return ($1, $2, $3); as everyone has suggested.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.