Skip to Content
Intermediate Perl, 2nd Edition
book

Intermediate Perl, 2nd Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
July 2012
Intermediate to advanced
396 pages
9h 16m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl, 2nd Edition

Chapter 8. Filehandle References

We’ve seen arrays, hashes, and subroutines passed around in references, permitting a level of indirection to solve certain types of problems. We can also store filehandles in references, and we can open filehandles on more than files. We look at the old problems then the new solutions.

The Old Way

In the olden days, Perl used barewords for programmer-defined filehandle names, and still does for the special filehandles such as STDIN, ARGV, and others. The filehandle is another Perl data type, although people don’t talk about it as a data type much since it doesn’t get its own special sigil. You’ve probably already seen a lot of code that uses these bareword filehandles:[17]

open LOG_FH, '>>', 'castaways.log'
  or die "Could not open castaways.log: $!";

What happens if we want to pass around these filehandles so we could share them with other parts of our code, such as libraries? You’ve probably seen some tricky looking code that uses a typeglob or a reference to a typeglob:[18]

log_message( *LOG_FH, 'The Globetrotters are stranded with us!' );

log_message( \*LOG_FH, 'An astronaut passes overhead' );

In the log_message routine, we take the first element off the argument list and store it in another typeglob. Without going into too many details, a typeglob stores pointers to all the package variables of that name. When we assign one typeglob to another, we create aliases to the same data. We can now access the data, including the details of the filehandle, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl & LWP

Perl & LWP

Sean M. Burke
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan

Publisher Resources

ISBN: 9781449343781Errata Page