What is the difference between \1 and $1 in a Perl regex?

后端 未结 3 1152
死守一世寂寞
死守一世寂寞 2020-12-01 17:19

What is the difference of doing \\1 as opposed to $1 if any, or are they interchangeable in all situations.

Example:

s/([a-z]+),afklol/$1,bck/;
#agai         


        
相关标签:
3条回答
  • 2020-12-01 17:34

    They give the same result, but $1 retains its value while \1 does not. Try this:

    s/([a-z]+),afklol/$1,bck/;
    print "\$1 is $1\n";
    #against
    s/([a-z]+),afklol/\1,bck/;
    print "\\1 is \1\n";
    
    0 讨论(0)
  • 2020-12-01 17:37

    Straight from perldoc perlre:

    Warning on \1 vs $1

    Some people get too used to writing things like:

    $pattern =~ s/(\W)/\\\1/g;
    

    This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it’s a dirty habit to get into. That’s because in PerlThink, the righthand side of an "s///" is a double- quoted string. "\1" in the usual double-quoted string means a control-A. The customary Unix meaning of "\1" is kludged in for "s///". However, if you get into the habit of doing that, you get yourself into trouble if you then add an "/e" modifier.

    s/(\d+)/ \1 + 1 /eg;        # causes warning under -w
    

    Or if you try to do

    s/(\d+)/\1000/;
    

    You can’t disambiguate that by saying "{1}000", whereas you can fix it with "${1}000". The operation of interpolation should not be confused with the operation of matching a backreference.

    Certainly they mean two different things on the left side of the "s///".

    0 讨论(0)
  • 2020-12-01 17:44

    I only use \1 on the rare occasions where I need the match to include a repeat of an earlier part of the pattern. e.g.

    /(foo|bar)baz\1/
    

    This would match "foobazfoo" or "barbazbar" but not "foobazbar". You can't use $1 there.

    In all other circumstances I use $1 and kin, because there are too many gotchas to using the other notation. See perlre for all the gory details.

    0 讨论(0)
提交回复
热议问题