Perl 101: Things Every Perl Programmer Should Know.

Performance

Perl lets you do just about whatever you want, and that includes things that may be slow or memory-intensive. Here's how to avoid some of these.

Use while to iterate over files, not for

Instead of slurping in all lines of a file and then working on the array with for, read in one line at a time with while.

These two loops are functionally the same:

    for ( <> ) {
        # do something
    }

    while ( <> ) {
        # do something
    }

The difference is that the for reads the entire file into a temporary array, and the while reads one at a time. For small files this may not matter, but for larger ones it may eat up all your available memory.

Using while in this case is just good practice.


Want to contribute?

Submit a PR to github.com/petdance/perl101


Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.