Perl Programming and Return Values
How do you return the value of a local variable array (or any variable for that matter) in perl. For instance. Must I return a reference to the array. That seems like it wouldn't work as well.
sub routine
{
my @array = ("foo", "bar");
return @array;
}
But this doesn't seem to work. How do you return values from local variables in perl?
My second related question is, how do I access a nested array as an array For instance. The previous question creates the need for this solution as well.
@nestedArray = ("hello", "there");
@array = ("the", \@nestedArray);
($variable1, $variable2) = values @array;
This is what I've tried
($variable3, $variable4) values 开发者_运维技巧$$variable2; ## This doesn't seem to work?
:-/
To your second question, you should read perlreftut to clear up your understanding of references.
Also, while keys
and values
will technically work on arrays, they're not really meant to be used on them. It's a red herring.
sub routine {
my @array = ( "foo", "bar" );
return @array;
}
print join "\n", routine();
The above indeed returns a list.
@nested_array = ( "hello", "there" );
@array = ( "the", \@nested_array );
print join "\n", ( $array[0], @{ $array[1] } );
Here, the first element of @array
is the
and the second element is an array reference. Therefore you have to dereference the second element as an array.
However, for ease, you could flatten the second array into a list:
@array = ( "the", @nested_array );
print join "\n", @array;
For the second one, this works:
($variable3, $variable4) = @$variable2;
Your first example seems to work like you have it.
You typically return references to non-scalar variables, or scalar values directly.
return $var
or
return \@var
or
return \%var
then dereference them as %$var or @$var or use arrow notation
$var->[0] or $var->{hash_key}
For first, you did the right thing. But I think you invoke the function in a scalar context, so you only got the number of elements in the list/array.
sub routine
{
my @array = ("foo", "bar");
return @array;
}
my $a = routine(); # a will be **2** instead of an array ("foo", "bar")
my @a = routine(); # a will be an array ("foo", "bar")
If you really need to return an array, and want to make sure the sub was invoked properly. You can use wantarray()
function.
sub routine
{
my @array = ("foo", "bar");
return @array if wantarray;
die "Wrong invoking context";
}
For second, you could use push;
@nestedArray = ("hello", "there");
@narray = ("the", "world");
push @narray, @nestedArray; # @narray is ("the", "world", "hello", "there")
精彩评论