Using the Special Underscore Filehandle

Every time you use stat, lstat, or a file test in a program, Perl has to go out to the system to ask for a stat buffer on the file (that is, the return buffer from the stat system call). That means if you want to know if a file is readable and writable, you’ll ask the system twice for the same information, which isn’t likely to change in a nonhostile environment.

This looks like a waste of time,[272] and can be avoided. Doing a file test, stat, or lstat on the special _ filehandle (the operand being a single underscore) tells Perl to use whatever happens to be lounging around in memory from the previous file test, stat, or lstat function, rather than going out to the operating system again. Sometimes this is dangerous: a subroutine call can invoke stat without your knowledge, blowing your buffer away. If you’re careful, you can save yourself a few unneeded system calls, thereby making your program faster. Here’s that example of finding files to put on the backup tapes again, using the new tricks you’ve learned:

    my @original_files = qw/ fred barney betty wilma pebbles dino bamm-bamm /;
    my @big_old_files;                       # The ones we want to put on backup tapes
    foreach (@original_files) {
      push @big_old_files, $_
        if (-s) > 100_000 and -A _ > 90;     # More efficient than before
    }

We used the default of $_ for the first test; this is as more efficient (except perhaps for the programmer), and it gets the data from the operating system. The second test uses the magic ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.