Section 10.12. Printing to Filehandles


10.12. Printing to Filehandles

Always put filehandles in braces within any print statement.

It's easy to lose a lexical filehandle that's being used in the argument list of a print:

     print $file $name, $rank, $serial_num, "\n";

Putting braces around the filehandle helps it stand out clearly:

      print {$file} $name, $rank, $serial_num, "\n";

The braces also convey your intentions regarding that variable; namely, that you really did mean it to be treated as a filehandle, and didn't just forget a comma.

You should also use the braces if you need to print to a package-scoped filehandle:

      print {*STDERR} $name, $rank, $serial_num, "\n";

Another acceptable alternative is to load the IO::Handle module and then use Perl's object-oriented I/O interface:

      use IO::Handle;     $file->print( $name, $rank, $serial_num, "\n" );     *STDERR->print( $name, $rank, $serial_num, "\n" );



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net