Документация
HTML CSS PHP PERL другое

Section 8.1.  The Old Way

 
Previous
Table of Contents
Next

8.1. The Old Way

In the olden days, Perl used barewords for filehandle names. The filehandle is another Perl data type, although people don't talk about it too much since it doesn't get its own special sigil. You've probably already seen a lot of code that uses these bareword filehandles .

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.

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 of 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, from another name. Then, when we use that name as a filehandle, Perl knows to look for the filehandle portion of the typeglob. We'd have a much easier time if filehandles had sigils!

sub log_message {
  local *FH = shift;

  print FH @_, "\n";
}

Notice the use of local there. A typeglob works with the symbol table, which means it's dealing with package variables. Package variables can't be lexical variables, so we can't use my. Since we don't want to stomp on anything else that might be named FH somewhere else in the script, we must use local to say that the name FH has a temporary value for the duration of the log_message subroutine and that when the subroutine finishes, Perl should restore any previous values to FH as if we were never there.

If all of that makes you nervous and wish that none of this stuff existed, that's good. Don't do this anymore! We put it in a section called "The Old Way" because there is a much better way to do it now. Pretend this section never existed and move on to the next one.


Previous
Table of Contents
Next
© 2000- NIV