When a Perl function returns an array is it possible to subscript the returned array?
my @tkeys = keys(%$someHashRef);
my $a0 = $tkeys[0];
# following not allowed by Perl
my $b0 = keys(%$someHashRef)[0];
Is there any way to extract an array element as a scalar from a function returning an array without using an intermediate array variable?
CodePudding user response:
You cannot subscript the subroutine/function call, but you can add parens and subscript those:
my ($value) = ( function() )[0];
Or using your example:
my $b0 = ( keys(%$someHashRef) )[0];
CodePudding user response:
You can use a list slice (( LIST )[ INDEXES ]
).
my $b0 = ( keys( %$someHashRef ) )[ 0 ];
Better yet, a list assignment would do the trick.
my ( $b0 ) = keys( %$someHashRef );
In this particular case, you can also use
my $b0 = each( %$someHashRef );
keys( %$someHashRef ); # Reset iterator.
This latter approach avoids creating a scalar for each key of the stash.