Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...