How can I selectively access elements returned by a Perl subroutine?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 03:56:04

问题


Say a Perl subroutine returns an array:

sub arrayoutput
{
    ...some code...
    return @somearray;
}

I want to access only a specific array element from this, say the first. So I could do:

@temparray=arrayoutput(argument);

and then refer to $temparray[0].

But this sort of short reference doesn't work: $arrayoutput(some argument)[0].

I am used to Python and new to Perl, so I'm still looking for some short, intuitive, python-like way (a=arrayoutput(some argument)[0]) to get this value. My Perl programs are getting very long and using temporary arrays like that seems ugly. Is there a way in Perl to do this?


回答1:


Slices

use warnings;
use strict;

sub foo {
    return 'a' .. 'z'
}

my $y = (foo())[3];
print "$y\n";

__END__

d

UPDATE: Another code example to address your comment. 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



回答2:


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];



回答3:


One way could be [(arrayoutput(some argument))]->[0].



来源:https://stackoverflow.com/questions/9810791/how-can-i-selectively-access-elements-returned-by-a-perl-subroutine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!