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