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

J. Bobby Lopez jbl at jbldata.com
Wed Dec 22 08:39:55 PST 2010


Thanks guys, this looks exactly like what I was looking for!


On Wed, Dec 22, 2010 at 10:54 AM, Mike Stok <mike at stok.ca> wrote:

> Maybe you want the e modifier:
>
> #!/usr/bin/env perl
> use strict;
> use warnings;
>
> my %replacement = (
>     a => 'd',
>     b => 'e',
>     c => 'f',
> );
>
> # this needs to be done with more care as you want to make sure that
> # abc appears before ab, but you get the idea...
> my $pattern = join('|', map { quotemeta } keys %replacement);
> print "pattern = $pattern\n";
>
> my $line = "*!*!* a *!*!* b *!*!* c *!*!*";
> $line =~ s/($pattern)/$replacement{$1}/ge;
>
> print $line."\n";
> __END__
>
> produces
>
> ratdog:tmp mike$ perl try.pl
> pattern = c|a|b
> *!*!* d *!*!* e *!*!* f *!*!*
>
> On Dec 22, 2010, at 10:44 AM, J. Bobby Lopez wrote:
>
> #!/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";
>
>
> --
>
> Mike Stok <mike at stok.ca>
> http://www.stok.ca/~mike/ <http://www.stok.ca/%7Emike/>
>
> The "`Stok' disclaimers" apply.
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20101222/35032fdf/attachment.html>


More information about the toronto-pm mailing list