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

Re: Swap foo and bar in text?

by GrandFather (Saint)
on Apr 18, 2012 at 05:00 UTC ( [id://965621]=note: print w/replies, xml ) Need Help??


in reply to Swap foo and bar in text?

I'd be inclined to use a lookup for the text to be replaced then use a regex driven substitution to do the heavy lifting:

#!/usr/bin/perl use strict; use warnings; my %edits = (foo => 'bar', bar => 'foo'); my $value = 'This string is all barfoo, but a little Perl should swap +the foos and bars'; my $match = '(' . join ('|', keys %edits) . ')'; $value =~ s/$match/$edits{$1}/g; print $value;

Prints:

This string is all foobar, but a little Perl should swap the bars and +foos
True laziness is hard work

Replies are listed 'Best First'.
Re^2: Swap foo and bar in text?
by Jim (Curate) on Apr 20, 2012 at 07:17 UTC

    Assuming "foo" and "bar" are metasyntactic variables, and that the real substrings could be anything, the use of quotemeta is in order:

    UPDATE: This paragraph should read…

    Assuming "foo" and "bar" are metasyntactic variables representing literal substrings, and that the real literal substrings could be any literal substrings (not regular expression patterns), then the use of quotemeta is in order:
    #!/usr/bin/perl use strict; use warnings; my %edits = ( '***' => 'stars', '|||' => 'stripes' ); my $value = '*** and |||'; my $match = '(' . join('|', map { quotemeta } keys %edits) . ')'; $value =~ s/$match/$edits{$1}/g; print $value; # Prints "stars and stripes"

    (I realize this example is no longer swapping anything. Sorry.)

    Jim

      the real substrings could be anything

      Indeed, which is why I removed the quote meta code from the example code before posting it - anything could include regular expressions which don't work so well when quoted.

      True laziness is hard work

        I don't understand what you're saying. Why did you remove quotemeta? Isn't it necessary as a precaution?

        Never mind. I figured out what you're saying.

        Jim

Log In?
Username:
Password:

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

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

    No recent polls found