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

The following line in LWP::RobotUA caught my eye:
...unless $cnf{from} && $cnf{from} =~ m/\@/;
Can anyone tell me why the "@" is escaped? The code prompted me to run this little test:
my $string = 'one@two.com'; if( $string =~ m/\@/ ) { print 'yes'; }
The above code prints 'yes' with and without the backslash. So what exactly is that backslash doing?

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff";
$nysus = $PM . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re: Backslashed "@" in reg exes
by Tanktalus (Canon) on Nov 13, 2005 at 03:36 UTC

    LWP::RobotUA may not need it there. But for longer strings, it's just a good habit to be in. For example,

    if ($string =~ m/@a/) {
    you'll get
    Possible unintended interpolation of @a in string at ./y.pl line 7.
    as a warning message under use warnings; (which you are doing, right?). But with the \, you'll get exactly what you wanted - an @-sigil followed by the letter a.

Re: Backslashed "@" in reg exes
by Zaxo (Archbishop) on Nov 13, 2005 at 04:36 UTC

    A stringy regex appearing in a match is treated as between double quotes. That makes perl attempt to interpolate both "@" and "$" followed by legal variable names.

    Interpolation is done before the regex is compiled. Since an array being interpolated is joined by the value of the $" variable, I like to use a local value of $" to construct big alternations:

    my $alt_foo_re = do { local $" = '|'; qr/@foo/; }; # same as: # my $alt_foo_re = do { # my $alt_foo = join '|', @foo; # qr/$alt_foo/; # }

    After Compline,
    Zaxo

Re: Backslashed "@" in reg exes
by pg (Canon) on Nov 13, 2005 at 03:59 UTC

    The backslash is not needed in this particular case, but it could be a good habit to have it there.

    Personally, I would have the backslash in front of the @, any time when interpolation is not desired, which seems a little bit more consistent to me.