Home: Perl Programming Help: Regular Expressions:
Nicer way to do this?



kencl
User

Oct 9, 2003, 4:35 AM


Views: 7231
Nicer way to do this?

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


Views: 7226
Re: [kencl] Nicer way to do this?

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


Views: 7151
Re: [kencl] Nicer way to do this?

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)