Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values from a Perl function call?

Tags:

perl

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.

like image 330
Bruc Walker Avatar asked Sep 09 '11 21:09

Bruc Walker


People also ask

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

You can also assign an array to hold the multiple return values from a Perl function. You do that like this: sub foo { return ('aaa', 'bbb', 'ccc'); } (@arr) = &foo(); print "@arr\n"; As you can see, most of the code is the same, except I now assign an array ( @arr ) to contain the three return values from my function.

Can you return multiple values from a function?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values.

How do I return an array from a function in Perl?

Returning a an array from a function in PerlCollect them in an array inside the function and then return the array. Behind the scenes Perl sees the content of this array and returns the elements as a list. Usually the caller will assign the result to an array as we did in the first call of fibonacci(8).


1 Answers

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.

like image 177
smackcrane Avatar answered Oct 25 '22 22:10

smackcrane