http://qs321.pair.com?node_id=826710

LanX has asked for the wisdom of the Perl Monks concerning the following question:

Honorable Monks,

After this discussion -> Re^6: while(){}continue{}; Useful? (Consistent!), I'm trying to understand the extended functionality of the new Given/When compared to the old workaround with For/Next.

As far as I understand,

  • In given/when I have to write a continue (statement not block!) where I omit the next statement. I need to "invert" the fall through.
  • In given/when I lose the continue-block which is always executed.
  • The when has an automatically built in smart match ~~. Nice ...but how can I take profit from this smart match if the parameter passed into given can only be a scalar?

    Maybe I missed something, please see the example code to understand what I mean:

    CODE:

    use feature "switch"; $,=$\="\t"; @test=qw/abc def abcdef nnn/; print "\n\n=== Given/When"; for (@test){ print "\nGIVEN($_):"; given($_) { when (/abc/) { print "abc";continue } when (/def/) { print "def" } when (/xyz/) { print "xyz" } default { print "default" } } } print "\n\n=== For"; for (@test){ for ($_){ print "\nFOR($_):"; if (/abc/) { print "abc"} if (/def/) { print "def" ;next} if (/xyz/) { print "xyz" ;next} print "default"; } } print "\n\n=== For/Continue"; # "simplifying" the former with post-ifs and && # using continue-block my @res; for (@test){ push (@res, "abc") if (/abc/); push (@res, "def") && next if (/def/); push (@res, "xyz") && next if (/xyz/); push (@res, "default"); } continue { print "\nFOR/CONT($_):",@res; @res=(); } print "\n\n === When smartmatch\n"; print "\n= GIVEN(\@test):\n"; given(@test) { print "whats tested is:",$_; when (/abc/) { print "abc";continue } when (/def/) { print "def" } when (/xyz/) { print "xyz" } default { print "default" } } print "\n= GIVEN(\\\@test):\n"; # does when act differently when a arr_reff is passed? given(\@test) { print "whats tested is:",$_; when (/abc/) { print "abc";continue } when (/def/) { print "def" } when (/xyz/) { print "xyz" } default { print "default" } } # whats the point of implicit smartmatch if only scalars can be testet +??? smartmatchingan array is different print "\nBUT: def ~~ \@test!" if @test ~~ /def/;
    OUTPUT:
    === Given/When GIVEN(abc): abc default GIVEN(def): def GIVEN(abcdef): abc def GIVEN(nnn): default === For FOR(abc): abc default FOR(def): def FOR(abcdef): abc def FOR(nnn): default === For/Continue FOR/CONT(abc): abc default FOR/CONT(def): def FOR/CONT(abcdef): abc def FOR/CONT(nnn): default === When smartmatch = GIVEN(@test): whats tested is: ARRAY(0x8a08a38) default = GIVEN(\@test): whats tested is: ARRAY(0x8a08a38) default BUT: def ~~ @test!

    Cheers Rolf

    UPDATE: extended given(Array) and given(Array_ref)

    Since given accepts arrays and automatically passes the ref without when reacting accordingly, I suppose it's a BUG!