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:
Nicer way to do this?

 



kencl
User

Oct 9, 2003, 4:35 AM

Post #1 of 3 (3453 views)
Nicer way to do this? Can't Post

Hi Folks,

Took me a while to realize that the pattern was gobbling up the trailing single pipe, but here's what I came up with. Does anyone see a "neater" way of doing this, or would you consider this a good solution?


Code
my $list = 'one|two|three|four'; 
my %changes = (one => 1, three => 3);

$list =~ s/\|/\|\|/g; # double up pipes
$list =~ s/((^|\|)(.*?)(\||$))/ exists($changes{$3}) ? $2 . $changes{$3} . $4 : $1/ge;
$list =~ s/\|\|/\|/g; # single up pipes

print $list; # produces 1|two|3|four


Thanks!

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


KevinR
Veteran


Oct 9, 2003, 8:56 PM

Post #2 of 3 (3448 views)
Re: [kencl] Nicer way to do this? [In reply to] Can't Post

another way to accomplish the same thing:


Code
my $list = 'one|two|three|four'; 
my %changes = (one => 1, three => 3);

foreach (keys %changes) {
$list =~ s/$_/$changes{$_}/g;
}
print $list;

-------------------------------------------------


(This post was edited by KevinR on Oct 9, 2003, 8:57 PM)


kencl
User

Feb 25, 2004, 1:14 PM

Post #3 of 3 (3373 views)
Re: [kencl] Nicer way to do this? [In reply to] Can't Post

Sometimes the solution is so obvious in hindsight. Figured I'd post it for the benefit of others.


Code
 $list =~ s/([^|]+)/exists($changes{$1}) ? $changes{$1} : $1/ge;  


>> 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 Feb 25, 2004, 1:15 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