Reputation: 103
Is there a better way to use tr/// on each element in an array than the following:
foreach (@list) {
tr/abc/xyz/;
}
I'm playing around with some stuff and I just can't get it out of my head that it doesn't look quite right/optimal. Maybe I'm just thinking of how conditionals can be used in a suffix form. Anyone know if there's a way to use the suffix form for tr/// or s///?
Upvotes: 3
Views: 2694
Reputation: 29854
If you want it as an expression, then I prefer (expression starts at map
).
my @trlist = map { tr/abc/xyz/; $_ } @list;
But the foreach
variety is probably the simplest way when you just want to change the items in the list:
tr/abc/xyz/ foreach @list;
Upvotes: 0
Reputation: 16869
I'm not a huge fan of for
as a statement modifier; not sure why, as there's nothing wrong with it, it just doesn't speak to me in that natural language way that other statement modifiers do. Because of that, I'd use map
instead:
map(tr/abc/xyz/, @list);
Purely a matter of preference, and I post it here as an example only. The other answers are fine, too.
Upvotes: 1
Reputation: 118158
Who uses parentheses with for
used as a statement modifier?
tr/abc/xyz/ for @list;
And, if you are golfing, you can save one more character by using y
instead of tr
.
Upvotes: 4
Reputation: 77420
Are you looking for:
tr/abc/xyz/ foreach (@list);
which basically works the same way as your code (each element of @list
is aliased to $_). In this case, you only get to meet Tim Toady and his fraternal twin Tom.
Upvotes: 10