Mapping substitutions

I am always wondering what is the best procedure to perform a substitution on a set of elements. While map could be a good idea,
@foo = map { s/bar/foo/g; $_ } @bar
is not legible. Probably better to use
@foo = @bar; s/bar/foo/g for @foo;
While I understand that the substitute operator return value is useful and relevant, I wonder if there is a cleaner syntax for this behavior with map.


I find the map to be more legible than putting two statements on one line.

While it doesn't help you now, there's a cool patch proposed for perl-5.13 to add a flag to s/// that will have it return the substituted value. It will eliminate the need for the extra "; $_" in the map.

You realize that map { ... } block is modifying @bar, right? If you don't want that, try List::MoreUtils::apply.

Here is another way to write it (which does not modify bar)

s/bar/foo/g foreach @foo = @bar;

You can put a "my" before @foo if needed. And of course "foreach" and "for" are interchangable, so you can use "for" there if you prefer.

Leave a comment

About Alberto Simões

user-pic I blog about Perl. D'uh!