Previous Page
Next Page

6.12. List Transformation

Use for instead of map when transforming a list in place.

There is, however, a particular case where map and grep are not better than an explicit for loop: when you're transforming an array in situ. In other words, when you have an array of elements or a list of lvalues and you want to replace each of them with a transformed version of the original.

For example, suppose you have a series of temperature measurements in Fahrenheit, and you need them in Kelvin instead. You could accomplish that transformation by applying a map to the data and then assigning it back to the original container:

    @temperature_measurements = map { F_to_K($_) } @temperature_measurements;

But the map statement has to allocate extra memory to store the transformed values and then assign that temporary list back to the original array. That process could become expensive if the list is large or the transformation is repeated many times.

In contrast, the equivalent for block can simply reuse the existing memory in the array:


    for my $measurement (@temperature_measurements) {
        $measurement = F_to_K($measurement);
    }

Note that this second version also makes it slightly more obvious that elements of the array are being replaced. To detect that fact in the map version, you have to compare the array names at both ends of a long assignment statement. In the for-loop version, the more compact statement:


        $measurement = F_to_K($measurement);

makes it easier to see that each measurement is being replaced with some transformed version of its original value.

    Previous Page
    Next Page