in reply to regular expression with @@/

According to perlretut ( here ):

The escape sequence \Q ...\E quotes, or protects most non-alphabetic + characters. For instance, 1. $x = "\QThat !^*&%~& cat!"; 2. $x =~ /\Q!^*&%~&\E/; # check for rough language It does not protect $ or @ , so that variables can still be substitute +d.
And perl.com says :
You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be matched. You'll need to write something like m/\Quser\E\@\Qhost/.
So, escaping should work :
use warnings; use strict; print "Yes!\n" if ( '$@' =~ m|\$\@| ); # prints "Yes!"
So maybe your regex isn't what you think - try a little debugging :
use warnings; use strict; my $string = '@@@'; if ( $string =~ m|\$\@| ){ print "Yes!\n"; } else { print "\'$string\' did not match...\n"; } # prints "'@@@' did not match..."
HTH

Update: Hmmm... damn slow typing... kennethk may have won the battle, but next time...(or not)!

Just a something something...

Replies are listed 'Best First'.
Re^2: regular expression with @@/
by almut (Canon) on Dec 07, 2009 at 18:32 UTC

    Actually, in this particular case, it should work with and without quoting, because /@@/ doesn't interpolate anything (as opposed to /@@x/ or /\Q@@x\E/, for example).

    #!/usr/bin/perl use warnings; use strict; $_ = 'foo@@bar'; print "matched\n" if /@@/; print "matched\n" if /\Q@@\E/; print "matched\n" if /\@\@/; __END__ matched matched matched

    Update: maybe a better (anchored) check, avoiding the potential gotcha of matching against a single-@ pattern:

    #!/usr/bin/perl use warnings; $_ = '@@'; print "1 matched\n" if /^@@\z/; print "2 matched\n" if /^\Q@@\E\z/; print "3 matched\n" if /^\@\@\z/; print "4 matched\n" if /^\Q@@x\E\z/; # doesn't match, because @x is be +ing interpolated print "5 matched\n" if /^@\@x\z/; # doesn't match, because there is + no 'x' in the string __END__ Possible unintended interpolation of @x in string at ./811585.pl line +10. Name "main::x" used only once: possible typo at ./811585.pl line 10. 1 matched 2 matched 3 matched

      Good call - as usual - I guess I more wanted to make the point that adding in some debugging is always useful, just so if things *don't* match, you can see exactly what they are, and tell if it is your input or your regex that isn't what you think...

      Just a something something...