Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by lamp (Chaplain)
on Oct 23, 2008 at 04:08 UTC ( #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? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2023-02-08 06:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (40 votes). Check out past polls.

    Notices?