perlperl-critic

Perl best practices: modifying array elements with map


I am using perlcritic to check code, trying to avoid errors.

I'm also trying to minimize new code loops like foreach, minimizing indentations, etc. I've found that an occasional map can help to make code more readable.

#!/usr/bin/env perl

use 5.040.2;
use warnings FATAL => 'all';
use autodie ':default';
use DDP {output => 'STDOUT', array_max => 10, show_memsize => 1};

my @arr = (1..9);
@arr = map {$_ /= 4} @arr;
p @arr;

this code works perfectly, as shown with DDP.

However, I got the following warning from perlcritic in bold:

Don't modify $_ in list functions at line 9, column 8. See page 114 of PBP. (Severity: 5)

I've read through perl best practices, and the examples that the author gave that show why map is a bad choice to modify arrays like that are much more complex than what I do.

Should I be using map, and disregard the warning from perlcritic?


Solution

  • You should use for instead:

    $_ /= 4 for @arr;
    

    It's even shorter and easier to read.

    You can use map to overwrite the original array:

    @arr = map { $_ / 4 } @arr;
    

    or faster with the expression syntax

    @arr = map $_ / 4, @arr;
    

    but for seems simpler. When you need to map each element to a different number of elements in the new array (including 0 elements), you can't use for and map is the way to go.