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:
Substitution using variables

 



tacallah
New User

Apr 28, 2004, 8:55 PM

Post #1 of 2 (2351 views)
Substitution using variables Can't Post

I have a function where I pass three strings, and I would like to use string substitution in this way.

$string1 = "One, Two, Three"; # some string

$string2 = ",[^,]*$"; # some pattern

$string3 = " and $1"; # what to replace pattern with

$string1 =~ s/$string2/$string3/;

print $string1; #prints "One, Two and $1"

# This will work without using $string3

$string1 =~ s/$string2/and $1/;

print $string1; #prints "One, Two and Three"

Is there a way I can have the "$1" in $string3 evaluate properly?

Thanks in advance for your help!


kencl
User

Jul 9, 2004, 8:13 PM

Post #2 of 2 (2285 views)
Re: [tacallah] Substitution using variables [In reply to] Can't Post

Cute little perl teaser. Try this on for size:


Code
$string = "One, Two, Three"; 

# note the capture brackets
$pattern = qr/,([^,]*)$/;

# single quotes otherwise $x's are interpolated
$replacement = ' and$1';

# supports as many matches as you can capture
@matches = $string =~ /$pattern/;

# defined test prevents warnings about uninitialized values in substitution iterator
$replacement =~ s/\$(\d+)/$matches[$1 - 1] if defined($matches[$1 - 1])/eg;

# now it works :)
$string =~ s/$pattern/$replacement/g;


>> If you can't control it, improve it, correlate it or disseminate it with PERL, it doesn't exist!

(This post was edited by kencl on Jul 9, 2004, 8:20 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