Section 11.5.  Using the Special Underscore Filehandle

Table of Contents

11.5. 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,[*] 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:

[*] Because it is. Asking the system for information is relatively slow.

    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 _ filehandle. For this test, the data left around after getting the file's size are used, which are what we want.

Testing the _ filehandle is different from allowing the operand of a file test, stat, or lstat to default to testing $_. Using $_ would be a fresh test each time on the current file named by the contents of $_, but using _ saves the trouble of calling the system again. Here is another case where similar names were chosen for radically different functions.

    Table of Contents
    © 2000- NIV