考虑下面的代码:
my @candidates = get_candidates($marker);
CANDIDATE:
for my $i (0..$#candidates) {
next CANDIDATE if open_region($i);
$candidates[$i] = $incumbent{ $candidates[$i]{region} };
}
什么是在第3行意义$#
?
考虑下面的代码:
my @candidates = get_candidates($marker);
CANDIDATE:
for my $i (0..$#candidates) {
next CANDIDATE if open_region($i);
$candidates[$i] = $incumbent{ $candidates[$i]{region} };
}
什么是在第3行意义$#
?
由于候选人是一个数组,$#candidates
是最大的指数(要素数 - 1)
例如:
my @x = (4,5,6);
print $#x;
将打印2
因为这是最大的指数。
注意,如果数组为空,$#candidates
将为-1
编辑:从perldoc perlvar
:
$# is also used as sigil, which, when prepended on the name of
an array, gives the index of the last element in that array.
my @array = ("a", "b", "c");
my $last_index = $#array; # $last_index is 2
for my $i (0 .. $#array) {
print "The value of index $i is $array[$i]\n";
}
啊......谢谢:) .. –
它是数组最后一个索引的值(在你的情况下它是最后一个候选索引)。
在perl中,我们有几种获取数组大小的方法,比如print @ arr,print标量(@arr),print $#arr + 1等等。没有理由,只是使用它。你会得到在与perl进一步联系的过程中熟悉perl中的一些默认用法。不像C++/java,perl使用大量的
特殊表达式来简化我们的编码,但有时它总是让我们更加困惑。
你应该在这里评论/提出问题之前已经经历了基本。 – pkm
@dev kumar:顺便说一下,'$#arrayname'也可以用在赋值的左边来改变最高索引号,扩展或截断一个数组(不经常使用)。 – cdarke
@cdarke谢谢:) –