Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: multiple (different) substitutions on same $foo

by Daruma (Curate)
on Aug 22, 2003 at 05:26 UTC ( #285675=note: print w/replies, xml ) Need Help??


in reply to multiple (different) substitutions on same $foo

Greetings!

You could put your pairs into a hash for easy reference...
use strict; use warnings; my $foo = "The frog kissed the woman and became a man."; print "$foo\n"; my %replace = ( "frog" => "toad", " man" => " boy", "woman" => "girl" ); foreach my $find (keys %replace) { $foo =~ s/$find/$replace{$find}/; } print "$foo\n";
-Daruma

Update changed variable names for easier reading...

Replies are listed 'Best First'.
Re^2: multiple (different) substitutions on same $foo (at once)
by tye (Sage) on Aug 22, 2003 at 05:36 UTC

    For a second, I thought you were suggesting what I was going to suggest... Close:

    my %repl= ( frog=>"toad", man=>"boy", woman=>"girl" ); $foo =~ s/(frog|man|woman)/$repl($1)/g;
    And you can even build the regex from the keys, if you like:
    my $re= join "|", map quotemeta($_), keys %repl;
    But the original code is probably both faster and simpler. (:

                    - tye

      However, the original poster specified one /g and two non-/g replacements. If that is the real intent, then a data-table solution would need to flag the repeatable replacements versus the singular replacements. If they all should be repeatable, then the data solutions offered are very useful.

      Also, a note to the original poster: s/man/boy/ would create a lot of strings like "read the fine boyual" in a general text. You may want to learn what the zero-width assertion \b does inside a regex. s/\bman\b/boy/g; s/\bmen\b/boys/g may help you out.

      --
      [ e d @ h a l l e y . c c ]

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://285675]
help
Chatterbox?
[Discipulus]: if known where i can read about the matter?
[choroba]: he's not really sick, we just got nobody to look after him today
[Discipulus]: create an account for him; we are funny baby sitters ;=) come here child, want to listen the typeglob tale?
[vrk]: choroba Oh, that's good.
[vrk]: Discipulus I don't know much about prime numbers, but wouldn't that kind of an answer be in a graduate-level number theory book?
[Discipulus]: my 8 yo daughter has two weeks of sleep disturbs.. we are gonna be crazy..

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2017-04-27 08:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (501 votes). Check out past polls.