RegExp Replace Using a Variable

From: Ones Self (nutgg001_at_sneakemail.com)
Date: 02/24/04

  • Next message: nobull_at_mail.com: "Re: Comments requested: brief summary of Perl"
    Date: 24 Feb 2004 10:02:22 -0800
    
    

    Hi all:

    I'm trying to replace using a regexp read from a file:

    $string = '123 456 789';
     # these two are usualy read from a file,
     # and so have to be in variables.
    $re = '([258])';
    $rep = '|$1|';

    $string =~ s/$re/$rep/g;

    I would like $string to be: 1|2|3 4|5|6 7|8|9
    but it is: 1|$1|3 4|$1|6 7|$1|9

    I understand why this is happening, but how do I make
    it do what I want?

    I've been reading around, I found an answer that almost works:
    $string = '123 456 789';
     # these two are usualy read from a file
    $re = '([258])';
    $rep = sub { "|$1|" };

    $string =~ s/$re/$rep->()/ge;

    This works, but it's not what I want. I want:
    $string = '123 456 789';
     # these two are usualy read from a file
    $re = '([258])';
    $repVar = '|$1|' # or "|$1|" doesn't work either way
    $rep = sub { $repVar };

    $string =~ s/$re/$rep->()/ge;

    But this doesn't work.

    Any help would be appritieted.
    Thanks.


  • Next message: nobull_at_mail.com: "Re: Comments requested: brief summary of Perl"