Zhao, Bingfeng wrote:
Hi list,
Hello,
I'm in trouble and hope who can work me out.
I want to so some replacements, so I want to keep all replacement
policies in a hash so that I can use them in a foreach loop, such as:
my %policies = (
"abc" => "def",
"jfk\s+" => "jfk ",
"(\d+)uu" => "uu\1"
You are using double quoted strings so the backslashes will be
interpolated away and you will be left with:
my %policies = (
"abc" => "def",
"jfks+" => "jfk ",
"(d+)uu" => "uu1"
You need to use single quoted strings instead. Also, the back-reference
\1 is only valid *inside* a regular expression, not in a replacement string:
my %policies = (
'abc' => 'def',
'jfk\s+' => 'jfk ',
'(\d+)uu' => 'uu$1',
#... many policies here
);
foreach (<DATA>)
{
s/$_/$policies{$_}/g for keys %policies;
You should use a while loop instead of a foreach loop to read from a
file. The current line is in the $_ variable. The substitution
modifies the $_ variable but it now contains one of the keys of
%policies and not the current line. You need to do something like this:
while ( my $line = <FILE> ) {
$line =~ s/$_/$policies{$_}/g for keys %policies;
Now, as to the use of back-references in the replacement string there
are some clues to be found at:
perldoc -q "How can I expand variables in text strings"
Which finally brings us to this:
while ( my $line = <FILE> ) {
$line =~ s/$_/qq{"$policies{$_}"}/eeg for keys %policies;
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/