你不小心絆上使用同一個列表,使用逗號而不是分號。看,當你添加第三個print語句會發生什麼:
print "\$_=[$_]\n";
與$one
爲1,我得到:
$_=[0]
...
$_=[]
...
$_=[1]
這是因爲在列表中項目。首先,你想要做什麼的,看起來會是這樣的:
for my $i ($one..($top_level - 1)) {
在這個循環中,$i
設置爲範圍的每個成員,然後執行循環。如果我們不支持該變量,則perl將其分配給$_
。
for ($one..($top_level - 1)) {
而且perl不會等待編譯列表,所以在它第一次執行之前它會執行所有的術語。
$i = $one;
# push actual $i returned by expression $i = $one
push @a, $i;
# result = [ $i=1 ]
# push boolean false => ''
push @a, ($i > $top_level);
# result = [ $i=1, '' ]
# push the return of $i--, NOT $i
push @a, ($i);
# result = [ $i=1, '', 1 ]
# decrement $i
$i--;
# result = [ $i=0, '', 1 ]
你可以發現這一點使用TIE-ED標:在運行環路輸出
my $one = 1;
tie my $i, 'Monitored', 'i';
tie my $top_level, 'Monitored', 'top_level', 5;
for($i = $one, $i > $top_level,$i--) # line 30
{
print "*LOOP*\n";
#print "\$i=$i\n"; <-- commented out to reduce noise
#print "\$one=$one\n";
print "\$_=[$_]\n"; # line 35
}
然後:
package Monitored;
sub TIESCALAR {
my ($class, $name, $value) = @_;
return bless { name => $name, value => $value }, $class;
}
sub FETCH {
my $self = shift;
Carp::carp "Reading \$$self->{name}...";
return $self->{value};
}
sub STORE {
my $self = shift;
my $value = shift;
Carp::carp "Storing \$$self->{name}=${\(defined($value) ? $value : 'undef')} ";
$self->{value} = $value;
}
而這個初始化在主線
Storing $i=1 at - line 30
Reading $top_level... at - line 30
Reading $i... at - line 30
Reading $i... at - line 30
Reading $i... at - line 30
Storing $i=0 at - line 30
*LOOP*
Reading $i... at - line 35
$_=[0]
*LOOP*
$_=[]
*LOOP*
$_=[1]
請注意,只有一個TI我在第35行,我們在循環開始後訪問$i
。
我不明白你在這裏得到什麼。如果你告訴我們'$ one','$ top_level'和你想要的輸出是什麼,那麼它可能會有所幫助,以及「值」意味着什麼? – Quentin