如何有选择地访问 Perl 子例程返回的元素? [英] How can I selectively access elements returned by a Perl subroutine?
问题描述
假设一个 Perl 子程序返回一个数组:
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);
然后参考$temparray[0]
.
但是这种简短的引用不起作用:$arrayoutput(some argument)[0]
.
But this sort of short reference doesn't work: $arrayoutput(some argument)[0]
.
我习惯了 Python 和 Perl 新手,所以我仍在寻找一些简短、直观、类似 Python 的方式(a=arrayoutput(some argument)[0]
)来获得这个值.我的 Perl 程序变得很长,使用这样的临时数组看起来很丑陋.Perl 有没有办法做到这一点?
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?
推荐答案
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
这篇关于如何有选择地访问 Perl 子例程返回的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!