Filehandles, Directory Handles, and Formats

The built-in functions open and opendir initialize a filehandle and a directory handle, respectively:

open(F, "/home/calvin");
opendir (D, "/usr");

The symbols F and D are user-defined identifiers, but without a prefix symbol. Unfortunately, these handles don’t have some basic facilities enjoyed by the important data types such as scalars, arrays, and hashes—you cannot assign handles, and you cannot create local handles:[20]

local (G);   # invalid 
G = F;       # also invalid

Before we go further, it is important to know that the standard Perl distribution comes with a module called FileHandle that provides an object-oriented version of filehandles. This allows you to create filehandle “objects,” to assign one to the other, and to create them local to the block. Similarly, directory handles are handled by DirHandle. Developers are now encouraged to use these facilities instead of the techniques described next. But you still need to wade through the next discussion because there is a large amount of freeware code in which you will see these constructs; in fact, the standard modules FileHandle, DirHandle, and Symbol, as well as the entire IO hierarchy of modules, are built on this foundation.

Why is it so important to be able to assign handles and create local filehandles? Without assignment, you cannot pass filehandles as parameters to subroutines or maintain them in data structures. Without local filehandles, you cannot create recursive subroutines ...

Get Advanced Perl Programming 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.