Perl Style: Use foreach() Loops

  • A foreach loop’s implicit aliasing and localizing can make for a powerful construct:

        foreach $e (@a, @b) { $e *= 3.14159 }
    
        for (@lines) {
            chomp;
            s/fred/barney/g;
            tr[a-z][A-Z];
        }
    
  • Remember you can copy and modify all at once:

        foreach $n (@square = @single) { $n **= 2 }
    
  • You can use hash slices to modify hash values, too:

        # trim whitespace in the scalar, the array,
        # and all the values in the hash
        foreach ($scalar, @array, @hash{keys %hash}) {
            s/^\s+//;
            s/\s+$//;
        }
    

Forward to Avoid Byte Processing
Back to Use $_ in Short Code
Up to index

Copyright © 1998, Tom Christiansen All rights reserved.

Tags

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub

TPRF Gold Sponsor
TPRF Silver Sponsor
TPRF Bronze Sponsor