in reply to Re^3: Smart enough for Smart Match??? (was "Understanding ...Given/When" )
in thread Understanding the benefit of Given/When ...

extending your code shows that there is a bug when matching ARRAY ~~ REGEX, do you agree?

use 5.010; use strict; use warnings; my @a=('abc',1); given (@a) { when (/abc/ ) { print '/abc/'."\n" ;continue} when ("abc" ) { print "abc\n" ;continue} #when (1 ) { print "#\n" ;continue} when (['abc',1]) { print "copy\n" ;continue} when (\@a ) { print "self\n" } } print "as it should be: ",@a~~/abc/;

OUTPUT

abc copy self as it should be 1

Cheers Rolf

PS: I have to go, too ...

Replies are listed 'Best First'.
Re^5: Smart enough for Smart Match??? (was "Understanding ...Given/When" )
by ikegami (Patriarch) on Mar 04, 2010 at 19:08 UTC
    You need to do when (qr/abc/). when(/abc/) appears to do when($_ ~~ ($_ =~ /abc/)).
    use 5.010; use strict; use warnings; my @a=qw(abc def); given (@a) { when (/abc/ ) { say '/abc/'; continue; } when (qr/abc/) { say 'qr/abc/'; continue; } } say '--'; if (@a ~~ /abc/ ) { say '/abc/'; } if (@a ~~ qr/abc/) { say 'qr/abc/'; }
    qr/abc/ -- /abc/ qr/abc/
    The discrepency is odd, though.
      But it is documented.

      But when EXPR is one of the below exceptional cases, it is used directly as a boolean:

      • [...]
      • a regular expression match, i.e. /REGEX/ or $foo =~ /REGEX/, or a negated regular expression match (!/REGEX/ or $foo !~ /REGEX/).
      • [...]

      It makes sense. It allows

      given ($x) { when (/abc/) { ... } when (/def/) { ... } when (/ghi/) { ... } }

      to mean

      if ($x =~ /abc/) { ... } elsif ($x =~ /def/) { ... } elsif ($x =~ /ghi/) { ... }
        What...

        OMG it took me a while to understand it ... yes it makes sense:

        use 5.010; use strict; use warnings; my @a=('abc'); given (@a) { print "$_\n"; when (/ARRAY/ ) { print "ARRAY\n" ;continue} # regex-match! when (/abc/ ) { print '/abc/'."\n" ;continue} # no match when (qr/abc/ ) { print 'qr/abc/'."\n" ;continue} # smart-match! }

        OUTPUT:

        ARRAY(0x8255a70) ARRAY qr/abc/

        Sigh ... do you agree that the docs could be more explicit? :)

        Cheers Rolf