Perl: Why Regex double backslash with character does not recognize string with single backslash with character? [closed]

Why does this Regex does not give 1?

>perl -e "$x = 'abcd\\e'; print \"$x\n\";  ($x =~ '\\e') ? print 1:print 0";
abcd\e
0

  • That gives a syntax error (Presumably because my shell doesn’t have a variable named x defined, so it’s replaced by an empty string)

    – 

  • 1

    Compare and contrast perl -E '$x = q{abcd\e}; say $x; ($x =~ q{\\\e}) ? say 1 : say 0' though you’d be better off rewording your question to put the code in a script file instead of the command line to avoid shell interpolation and escaping.

    – 

  • 1

    You need more backslashes if you run this from the shell. E.g. : perl -e "\$x = 'abcd\\e'; print \"\$x\n\"; (\$x =~ '\\\\\\e') ? print 1:print 0"; works for me

    – 

  • @Shawn and @Hakon: OK, you both answered my question. It is a shell issue. I wrote a script and run your code (q{\\\e} or ‘\\\e’) and it gives me 1. But why 3 backslash and not only two? And why the minus point for such a simple question where the solution seems not so trivial?

    – 




  • @giordano “But why 3 backslashes and not only two?” Inside q{} two consecutive backslashes becomes a single backslash, see perldoc.perl.org/perlop#Quote-Like-Operators

    – 

The Regex ($x =~ '\e') doesn’t match because '\e' tries to find a literal backslash followed by 'e.' However, in your string $x ('abcd\e'), there’s an actual backslash before 'e.' To fix this, use a single backslash in your regular expression, like this:

Fixed Regex:

perl -e "$x = 'abcd\\e'; print \"$x\n\";  ($x =~ '\\\\e') ? print 1 : print 0";

With this adjustment, the Regex will indeed locate the backslash followed by 'e' within the string, and your script will produce the anticipated outcome of 1.

Leave a Comment