in reply to trouble with @ in a regular expression

perl -e "my $str='foo@bar'; if ($str =~ /@/){ print \"No need to escap +e the \@ in a regex\";}" No need to escape the @ in a regex

or, more nearly parallel to your problem statement, anchoring the start of the line:

perl -e "my $str='@bar'; if ($str =~ /^@/){ print \"No need to escape +the \@ in a regex\";}" No need to escape the @ in a regex

Replies are listed 'Best First'.
Re^2: trouble with @ in a regular expression
by AnomalousMonk (Archbishop) on Mar 29, 2012 at 23:16 UTC

    Is too (if it can look like an interpolable variable).

    >perl -wMstrict -le "my $str='foo@bar'; if ($str =~ /@b/){ print 'No need to escape the @ in a regex'; } " Possible unintended interpolation of @b in string at ... Global symbol "@b" requires explicit package name at ... Execution of -e aborted due to compilation errors.
      Good catch! + +

      Note that it's the invocation of strict and warnings (-w) that illuminates my error.

        Even with warnings and strictures, Perl is quite happy with an @ if it cannot possibly be a variable.

        >perl -wMstrict -le "my $s = 'foo@bar'; print 'No need to escape lone @ in regex' if $s =~ /@ bar/x; " No need to escape lone @ in regex