I've got a piece of code that works fine. It basically loops through each element of a hash using foreach()
and applies a transformation to it using a regular expression, like so :
foreach my $key ( keys( %{$results} ) ) {
$results->{$key}{uri} =~ s/\".*\/(.*\.*(gif|jpe?g|png))\"/\/resources\/uploads\/$1/gi;
}
$results is a hashref returnd by DBI's fetchall_hashref()
function.
Just out of curiosity, I wanted to see if I could rewrite it using map()
instead, as shown below :
map {
$results{$_}{uri} =~ s/\".*\/(.*\.*(gif|jpe?g|png))\"/\/resources\/uploads\/$1/gi
} keys %{$results};
Unfortunately, that doesn't work. I've tried all sorts of things but so far without success. Anybody knows how to do this? Thanks.
UPDATE
The corrected code, as answered by ysth:
map {
$results->{$_}{uri} =~ s/\".*\/(.*\.*(gif|jpe?g|png))\"/\/resources\/uploads\/$1/gi
} keys %{$results};
and the improved version with less leaning toothpicks suggested by Sinan Ünür
map {
$results->{$_}{uri} =~ s{".*/(.*\.*(gif|jpe?g|png))"}{/resources/uploads/$1}gi
} keys %{$results};