Dynamic regexp

Discussion in 'Perl' started by Winston Smith, Nov 14, 2003.

  1. 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.
    Winston Smith, Nov 14, 2003
    #1
    1. Advertising

  2. Winston Smith wrote:

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


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


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


    --
    Klaus Johannes Rusch

    http://www.atmedia.net/KlausRusch/
    Klaus Johannes Rusch, Nov 14, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Greg Hurrell
    Replies:
    4
    Views:
    157
    James Edward Gray II
    Feb 14, 2007
  2. Mikel Lindsaar
    Replies:
    0
    Views:
    478
    Mikel Lindsaar
    Mar 31, 2008
  3. Joao Silva
    Replies:
    16
    Views:
    354
    7stud --
    Aug 21, 2009
  4. Uldis  Bojars
    Replies:
    2
    Views:
    190
    Janwillem Borleffs
    Dec 17, 2006
  5. Matìj Cepl

    new RegExp().test() or just RegExp().test()

    Matìj Cepl, Nov 24, 2009, in forum: Javascript
    Replies:
    3
    Views:
    177
    Matěj Cepl
    Nov 24, 2009
Loading...

Share This Page