Hey. In Python I can do this:
def fnuh():
a = "foo"
b = "bar"
return a,b
Can I return a list in a similarly elegant way in perl, especially when the return type of the subroutine should be a reference to an array?
I know I can do
sub fnuh {
my $a = "foo";
my $b = "bar";
my $return = [];
push (@{$return}, $a);
push (@{$return}, $b);
return $return;
}
But I bet there is a better way to do that in Perl. Do you know it?
Sure, just slap a \\
in front of the list to return a reference.
Or make a new arrayref with [ list elements ]
.
In your example,
sub f1 {
my $a = "foo";
my $b = "bar";
return [ $a, $b ];
}
sub f2 {
my $a = "foo";
my $b = "bar";
push @return, $a, $b;
return \@return;
}
Please see perldoc perlreftut and perldoc perlref for more about references. There is also a data structures cookbook at perldoc perldsc .
You may also want to read this question in the perlfaq (thanks brian): "What's the difference between a list and an array?"
Python automatically packs and unpacks tuples around an assignment simulating lists. In Perl, you can write it the same way, returning a list.
sub fnuh {
my $a = 'foo';
my $b = 'bar';
$a, $b
}
then to use the result:
my ($x, $y) = fnuh;
or if you need the reference:
my $ref = [ fnuh ];
You can get the same function as Python by explicitly testing whether the context wants an array with the function wantarray
.
sub fnuh {
my $a = 'foo';
my $b = 'bar';
return wantarray ? ( $a, $b ), [ $a, $b ];
}
Or if you want to do this a lot, you could write a function that will be able to read the same context, as long as you have not altered it.
sub pack_list {
my $want = wantarray;
return unless defined $want; # void context
return $want ? @_ : \@_;
}
Then call it like this:
return pack_list( $a, $b );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.