[tpm] Search/Replace multiple patterns in a single line, in a single pass?
J Z Tam
jztam at yahoo.com
Wed Dec 22 09:54:53 PST 2010
I'm with Richard:
Why not just tr the line?
DB<1>
main::(bobbyRegex1.pl:10): my $line = "*!*!* a *!*!* b *!*!* c *!*!*";
DB<1>
main::(bobbyRegex1.pl:14): my $pattern = '(a)+\s.*(b)+\s.*(c)+\s'; # kinda/
sorta, replaces stuff between patterns also
DB<1> $expectedMatches = $line =~ tr/abc/def/;
DB<3> x $expectedMatches
0 3
DB<4> x $line
0 '*!*!* d *!*!* e *!*!* f *!*!*'
DB<5>
--- On Wed, 12/22/10, Richard Dice <richard.dice at gmail.com> wrote:
From: Richard Dice <richard.dice at gmail.com>
Subject: Re: [tpm] Search/Replace multiple patterns in a single line, in a single pass?
To: "J. Bobby Lopez" <jbl at jbldata.com>
Cc: "Toronto Perl Mongers" <tpm at to.pm.org>
Received: Wednesday, December 22, 2010, 12:20 PM
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
_______________________________________________
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/ec057901/attachment.html>
More information about the toronto-pm
mailing list