7stud has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I'm using given-when in a for loop:
use strict; use warnings; use 5.010; my @arr = (1, 2, 4); for (@arr) { print "$_: "; when (1) {print "1"; continue} when ($_ % 2 == 0) {print "divisible by 2"; continue} when ($_ % 4 == 0) {print ", divisible by 4"} say "\n------end this iteration"; }
Every time through the loop the last say statement executes--except the last time through the loop. Why? If I add a continue statement to the last when block, then the last line will execute for the last iteration of the loop.
Also, "Learning Perl 5th" says there is an implicit break at the end of each when block, but I get errors if I do this:
use strict; use warnings; use 5.010; my @arr = (1, 2, 4); for (@arr) { print "$_: "; when (1) {print "1"; break} when ($_ % 2 == 0) {print "divisible by 2"; break} when ($_ % 4 == 0) {print ", divisible by 4"; break} say "\n------end this iteration"; } --output:-- Can't "break" in a loop topicalizer at 1perl.pl line 10. 1: 1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: given-when last time through loop?
by moritz (Cardinal) on Nov 19, 2009 at 13:57 UTC | |
by 7stud (Deacon) on Nov 19, 2009 at 14:10 UTC | |
by moritz (Cardinal) on Nov 19, 2009 at 14:47 UTC | |
by ikegami (Patriarch) on Nov 19, 2009 at 15:36 UTC | |
by 7stud (Deacon) on Nov 19, 2009 at 15:36 UTC | |
by moritz (Cardinal) on Nov 19, 2009 at 15:57 UTC | |
|