Amit Saxena wrote:On Tue, Jul 1, 2008 at 4:19 PM, John W. Krahn wrote:Amit Saxena wrote:
Why don't use perl "s" operator with "e" option ?
$str =~ s/([^ ]+)/$hash{\1}/ge
You don't need the /e option to interpolate a variable in a double quoted
string and you should use $1 instead of \1 inside a double quoted string:
$str =~ s/([^ ]+)/$hash{$1}/g
I am not only expanding a variable but also using that expanded variable as
a key to ultimately find the value. That's why I need "e".
A single hash element is a scalar variable, and John is correct that you don't
need the /e option to interpolate it if you key it properly with $1 instead of
\1. Try it.
Secondly, inside text that is to be substituted, I can use \1 as well. And
moreover, for this, I don't need double quotes. If i purposefully
incorporate double quotes, then I need $1.
John's point wasn't that double-quotes were needed, but that right-hand side of
a substitution behaves as a double-quoted string. I don't understand why you
think you need $1 if you somehow involve double quotes explicitly.
This is from
perldoc perlre
You would do well do read and understand it so that your advice on this group
can agree with the documentation.
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///".
In addition,
- The usual way of writing /([^ ]+)/ is /(\S+)/, and although the two are
slightly different I doubt if you wanted your class to include tabs and
formfeeds?
- Your code will simply delete any word in the string that doesn't appear as a
hash key, and will also throw warnings each time it does it.
Rob