in reply to given/when one case prefixes another

You could modify $_ inside the given-when scope to some magic value indicating the common ending code needs to be executed. Like so:
#!/usr/bin/perl use warnings; use strict; use v5.10; my @data = ('foo', 'bar', 'baz'); for my $element (@data) { given ($element) { when ('foo') { # Do foo things print("foo here\n"); # force common ending routine $_ = 'MAGIC_foobar'; continue; } when ('bar') { # Do bar things print("bar here\n"); # force common ending routine $_ = 'MAGIC_foobar'; continue; } when ('baz') { # Do baz things print("baz here\n"); } when ('MAGIC_foobar') { # Do common ending things here print("foobar ending here\n"); } } }
This produces the following output:
foo here foobar ending here bar here foobar ending here baz here

Replies are listed 'Best First'.
Re^2: given/when one case prefixes another
by John M. Dlugosz (Monsignor) on Apr 26, 2011 at 08:41 UTC
    Ah, so continue means "keep checking for more matches"? The docs, like the previous poster, said it falls through to the next case. That's not at all the same thing!

      Maybe "not the same thing" but definitely not "'keep checking for more matches'" (within the current when, anyway).

      At least, not in the same sense as the /g modifier in a regex. Observe:

      #!/usr/bin/perl use strict; use warnings; use 5.012; # 901284 my $count=0; my $foo = "X x y y x y Z"; say "First, with a simple substitution '/g'"; my $simplecount = $foo =~ s/x/o/g; say " \$foo: $foo; \n \$simplecount: $simplecount (i.e., 'x's changed) +"; $foo =~ s/o/x/g; say "\$foo restored: $foo \n"; say 'Now, with given/when and =~ /x/g'; given( $foo ) { when ( $foo =~ /x/g ) { say "\$foo contains an x"; $count++; say "\$foo: $foo; \n \$count: $count;"; continue } when ( /y/ ) { say "\n \$foo contains a y"; } default { say "$foo does not contain a y"; } } say "\n Final \$count of 'x' in given/when matching 'x': $count"; say "\n $foo";

      OUTPUT:

      First, with a simple substitution '/g' $foo: X o y y o y Z; $simplecount: 2 (i.e., 'x's changed) $foo restored: X x y y x y Z Now, with given/when and =~ /x/g $foo contains an x $foo: X x y y x y Z; $count: 1; $foo contains a y Final $count of 'x' in given/when matching 'x': 1 X x y y x y Z

      One possible reading is that continue's precedence terminates the matching. Perhaps a wiser head will explain (and correct, as necessary).

      Update: typo fixed (from /s/g to /x/g) at line 15 and in the output. Gnahh!