CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions: Re: [ericm] replacement with backreference: Edit Log



eWish
User

Aug 8, 2007, 10:11 PM


Views: 3753
Re: [ericm] replacement with backreference

To me this would be the way to go.

Code
my $string = 'Name:Address:Phone';  
my $pattern = ':';
my $replacement = '--';
$string =~ s/$pattern/$replacement/g;


or you could also do


Code
my $string = 'Name:Address:Phone';   
print join('--', split(/:/, $string));



If you are not wanting something so trivial as a replacement of -- or :: etc... and you really need to catch a particular pattern then I am not sure how it will work with the backreferences in a variable like $replacement.

The backreference's seem to be lost in translation, I tested some code and $1, $2 and $3 never contained anything when doing:

my $replacement = "$1--$2--$3";

Edit:
You could do:

Code
my $string = 'Name:Address:Phone'; 
my $pattern = '(\w+):(\w+):(\w+)';
my $replacement = '--';

my $new_string = $string;
$new_string =~ s/$pattern/$1$replacement$2$replacement$3/;

print $new_string;



(This post was edited by eWish on Aug 8, 2007, 10:40 PM)


Edit Log:
Post edited by eWish (User) on Aug 8, 2007, 10:40 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives