[tpm] Search/Replace multiple patterns in a single line, in a single pass?

J. Bobby Lopez jbl at jbldata.com
Wed Dec 22 07:44:46 PST 2010


Hey all,

I'm trying to figure something out, but having some trouble.  I'm trying to
replace multiple patterns via capture buffers, with multiple replacements
contained in a hash.

Looking at the code below, you can see that the patterns I'd like to match
are contained in $regex just fine, however I'd like to have mutiple
$replacement{$#} 's depending on the number of patterns I'm trying to
replace.

==== begin-code ===
#!/usr/bin/env perl
use strict;
use warnings;

my %replacement;
$replacement{'a'} = 'd';
$replacement{'b'} = 'e';
$replacement{'c'} = 'f';

my $line = "*!*!* a *!*!* b *!*!* c *!*!*";

#my $pattern = '(a)|(b)|(c)'; # Doesn't work, only matches first pattern
my $pattern = '(a).*(b).*(c)'; # kinda/sorta, replaces stuff between
patterns also

#$line =~ s/$pattern/$replacement{$1}/; # <-- here's where I'm having
difficulty
$line =~ s/$pattern/$replacement{$1} $replacement{$2} $replacement{$3}/; #
kinda/sorta

#$line =~ m/$pattern/;
#print "$1, $2, $3\n";

print $line."\n";
==== end-code ===


Either I'm missing something, or this isn't actually possible, and I'll have
to loop through the patterns and replace them individually.

Thoughts?

-Bobby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20101222/bb9578d6/attachment.html>


More information about the toronto-pm mailing list