Thursday, April 11, 2019

Perl: pitfall in returning two results with an array from a subroutine


When the results returning from a Perl subroutine contain an array, we may not get the result we want. Consider this code:

sub return_two_results {
    my @arr = (1, 2, 3, 4);
    my $str = "Hello";
   
    return (@arr, $str);
}

my (@ar, $st) = return_two_results();

print "ar:", join(", ", @ar), "\n";
print "st:", $st, "\n";


The result will be:
ar:1, 2, 3, 4, Hello
st:


The string "Hello" that is supposed to be the second result is returned in the array as the first result.

To resolve that, we can simply swap the array and string being returned. i.e.:

sub return_two_results {
    my @arr = (1, 2, 3, 4);
    my $str = "Hello";
   
    return ($str, @arr);
}

my ($st, @ar) = return_two_results();

print "ar:", join(", ", @ar), "\n";
print "st:", $st, "\n";

Now, we can get what we expected:
ar:1, 2, 3, 4
st:Hello


No comments:

 
Get This <