当前位置: 动力学知识库 > 问答 > 编程问答 >

Perl: Is there a way to use a hashref as a for-loop iteration variable?

问题描述:

You can do something like:

my $hr = {start=>3, end=>20};

for my $i ($hr->{start}..$hr->{end}){

...

}

But what if you don't want $i and instead want to use and increment the $hr->{start} value? The following won't work:

for $hr->{start} ($hr->{start}..$hr->{end}){

...

}


Alternatives:

  1. The following is one way to handle it, but is there a way to include the incrementation with the iteration variables?

    for ($hr->{start}..$hr->{end}){

    ...

    $hr->{start}++;

    }

  2. Another way using a c-for-loop:

    for ( ; $hr->{start} <= $hr->{end} ; $hr->{start}++){

    ...

    }

网友答案:

A Perl-style for/foreach VAR (LIST) construction won't do what you want. The index variable must be a simple scalar. More importantly, the index variable is always localized and aliased to the items in the LIST, and its meaning is lost outside the foreach loop.

my $foo = 42;
for $foo (1..10) {
   ...
}
print $foo;      # 42

But within a C-style for loop you can do anything you want with the expressions.

$hr = { start => 1 , end => 10 };
for ( ; $hr->{start} <= $hr->{end} ; $hr->{start}++ ) {
    ...
}
print $hr->{start};       # now it is 11
网友答案:

Increment at end of loop:

for (; $hr->{start} <= $hr->{end}; ++$hr->{start}) {
   ... 
}

Increment at start of loop:

while ($hr->{start}++ <= $hr->{end}) {
   ... 
}
网友答案:

Well, you could always:

for ($hr->{start}..$hr->{end}){
  $hr->{start} = $_;
  ...
}

Basically, if you don't stick a "my" in front of the variable, perl sticks an implicit "local" in front of the loop variable. And since you can't localize a reference (that wouldn't make any sense, if you think about it), you can't use a reference as the iterator.

分享给朋友:
您可能感兴趣的文章:
随机阅读: