Zhao, Bingfeng wrote:
Hi list,
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"
#... many policies here
);
foreach (<DATA>)
{
s/$_/$policies{$_}/g for keys %policies;
print;
}
But perl complains, so I update it as:
my %policies = (
qr/abc/ => "def",
qr/jfk\s+/ => "jfk ",
qr/\d+uu/ => "uu\1"
);
foreach (<DATA>)
{
s/$_/$policies{$_}/g for keys %policies;
print;
}
The result is wrong, since I got \1 instead of matched part. I update it
again as:
my %policies = (
qr/abc/ => qr/def/,
qr/jfk\s+/ => qr/jfk /,
qr/\d+uu/ => qr/uu\1/
);
foreach (<DATA>)
{
s/$_/$policies{$_}/g for keys %policies;
print;
}
Perl complains again that \1 is not refer to anything. So I try to put
the whole s/// into a list:
my $policies = (
s/abc/def/g,
s/jfk\s+/jfk /g,
s/\d+uu/uu\1/g
);
foreach (<DATA>)
{
$_ =~ $_ for $policies;
print;
}
It generates more errors. So my question, how can I save my replacement
policies in perl data structure so that I can use it just as single one?
I suggest:
apply_policies($value);
sub apply_policies {
for ($_[0]) {
s/abc/def/;
s/jfk\s+/jfk /;
s/(\d+)uu/uu\1/;
}
}
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/