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

后端 未结 3 665
余生分开走
余生分开走 2020-12-10 12:56

Say a Perl subroutine returns an array:

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

I want to access only a specific arr

相关标签:
3条回答
  • 2020-12-10 13:38

    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];
    
    0 讨论(0)
  • 2020-12-10 13:39

    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
    
    0 讨论(0)
  • 2020-12-10 13:47

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

    0 讨论(0)
提交回复
热议问题