Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

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

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/;
#against
s/([a-z]+),afklol/1,bck/;

They both give the same result but is there any difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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///".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...