Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Replace after match in regex (key value subsitution)

by lamp (Chaplain)
on Oct 23, 2008 at 04:08 UTC ( [id://718941]=note: print w/replies, xml ) Need Help??


in reply to Replace after match in regex (key value subsitution)

The following eg. code will substitute the '%fixers' hash key with corresponding value from '$text'.
#!/usr/bin/perl -w use strict; my %fixers=( 'amazon.com' => 'danube.com', 'ibm.com' => 'bm.com', ); my $text = qq( Blah <a href="http://amazon.com/foo">one</a> <a href="http://ebay.com/foo">two</a> ); map { $text =~ s/$_/$fixers{$_}/; }keys %fixers; print $text;

Replies are listed 'Best First'.
Re^2: Replace after match in regex (key value subsitution)
by ikegami (Patriarch) on Oct 23, 2008 at 04:28 UTC
    Almost.
    • You forgot to convert the text to a regexp pattern.
    • You only replace the first instance.
    • And since I'm already changing the line, I'll remove the useless use of map.
    $text =~ s/\Q$_\E/$fixers{$_}/g for keys %fixers;

    It could still be improved if it's going to be done repeatedly.

    my ($re) = map qr/$_/, join '|', map quotemeta, keys %fixers; while (...) { ... $text =~ s/$re/$fixers{$_}/g for keys %fixers; ... }

    Or even better for pre-5.10

    use List::Regexp qw( ); my $re = List::Regexp->new()->list2re( keys %fixers ); while (...) { ... $text =~ s/$re/$fixers{$_}/g for keys %fixers; ... }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://718941]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-23 19:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found