How can I selectively access elements returned by a Perl subroutine?
Pull off the first argument only via list context:
my ( $wanted ) = array_returning_sub( @args );
TIMTOWTDI with a slice:
my $wanted = ( array_returning_sub( @args ) )[0];
Both styles could be extended to extract the n'th element of the returned array, although the list slice is a bit easier on the eye:
my ( undef, undef, $wanted, undef, $needed ) = array_returning_sub( @args );
my ( $wanted, $needed ) = ( array_returning_sub( @args ) )[2,4];
Slices
use warnings;
use strict;
sub foo {
return 'a' .. 'z'
}
my $y = (foo())[3];
print "$y\n";
__END__
d
Alternately, you do not need an intermediate variable:
use warnings;
use strict;
sub foo {
return 'a' .. 'z'
}
print( (foo())[7], "\n" );
if ( (foo())[7] eq 'h') {
print "I got an h\n";
}
__END__
h
I got an h
One way could be [(arrayoutput(some argument))]->[0]
.