Reputation: 7427
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?
:-/
Upvotes: 2
Views: 932
Reputation: 6784
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")
Upvotes: 0
Reputation: 165606
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.
Upvotes: 3
Reputation: 74292
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;
Upvotes: 2
Reputation: 4829
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}
Upvotes: 0
Reputation: 68172
For the second one, this works:
($variable3, $variable4) = @$variable2;
Your first example seems to work like you have it.
Upvotes: 0