Dynamic regexp

W

Winston Smith

Hi everybody,

I'm looking for a way to make a batch of s/// substitutions. As a code
sample is worth a thousand words, let see what me code is presently :

---

my @rules = (
['^HELLO (.*)$', 'BONJOUR $1'],
# ... lots of other rules
);

foreach my $rule (@rules) {
if ($string =~ s/$rule->[0]/$rule->[1]/ei) {
last;
}
}

---

With this code, 'HELLO WINSTON' becomes 'BONJOUR $1' and not 'BONJOUR
WINSTON' as I'd like.

I tried to put double quotes in the table of strings but it makes no
difference.

I also tried to put a second e option to the s/// operator so that the
string 'BONJOUR $1' is reinterpolated. Then I get the message 'Use of
uninitialized value in substitution iterator ...' as if $1 is not
defined. But if I put a
print $1;
instruction just before the instruction
last;
it works and actually print 'WINSTON' if I use the same exemple than
previously.

Thank you in advance for your help.
 
K

Klaus Johannes Rusch

Winston said:
I'm looking for a way to make a batch of s/// substitutions. As a code
sample is worth a thousand words, let see what me code is presently :

---

my @rules = (
['^HELLO (.*)$', 'BONJOUR $1'],
# ... lots of other rules
);

foreach my $rule (@rules) {
if ($string =~ s/$rule->[0]/$rule->[1]/ei) {
last;
}
}

my @rules = (
['^HELLO (.*)$', '"BONJOUR $1"'],
);


foreach my $rule (@rules) {
if ($string =~ s/$rule->[0]/eval($rule->[1])/ei) {
last;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top