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

Stuart Watt stuart at morungos.com
Wed Dec 22 07:54:01 PST 2010


On 22/12/2010 10:44 AM, J. Bobby Lopez wrote:
> 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.
I think you need the "e" flag if there is perl code in the replacement 
part. Just stick "e" on the end of your substitutions. You'll also need 
to use the . operator to concatenate as per:

$line =~ 
s/$pattern/$replacement{$1}.$replacement{$2}.$replacement{$3}/e; # kinda 
works now maybe

All the best
Stuart

>
> ==== 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
>
>
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm

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


More information about the toronto-pm mailing list