...
| Code Block | ||||
|---|---|---|---|---|
| ||||
my $value;
my @list = (1, 2, 3);
for $value (@list) {
if ($value % 2 == 0) {
last;
}
}
print "$value is even\n";
|
However, the loop treats the iteration variable $value as local. So when it exits the list, $value regains the value it had before the loop. Since it was uninitialized before the loop, it therefore remains undefined afterwards, and the final print statement prints {{ is even}}.
Compliant Solution (Expanded
...
Loop)
This compliant solution correctly prints 2 is even. It accomplishes this by moving the print statement inside the loop, and therefore never refers to $value outside the loop.
| Code Block | ||||
|---|---|---|---|---|
| ||||
my @list = (1, 2, 3);
for my $value (@list) {
if ($value % 2 == 0) {
print "$value is even\n";
last;
}
}
|
Compliant Solution (
...
External Variable)
This compliant solution preserves the value of $value by assigning it to a lexical variable defined outside the loop. It still declares $v to be private to the loop using my.
| Code Block | ||||
|---|---|---|---|---|
| ||||
my @list = (1, 2, 3);
my $value;
for my $v (@list) {
if ($v % 2 == 0) {
$value = $v;
last;
}
}
print "$value is still even\n";
|
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
my @list = (1, 2, 3);
for ($value = 1; $value < 4; $value++) {
if ($value % 2 == 0) {
last;
}
}
print "$value is still even\n";
|
...