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

Richard Dice richard.dice at gmail.com
Wed Dec 22 09:20:25 PST 2010


Two thoughts.

Why aren't you using the 'global' switch on the substitution, like s///g ?

Second, if the substitutions in your real code are as simple as in your example code, you should consider the transliterate operator rather than the substitution operator, per $foo =~ tr///;

Sent from my iPhone

On 2010-12-22, at 10:44 AM, "J. Bobby Lopez" <jbl at jbldata.com> 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.
> 
> ==== 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


More information about the toronto-pm mailing list