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

Section 8.2.  The Improved Way

 
Previous
Table of Contents
Next

8.2. The Improved Way

Starting with Perl 5.6, open can create a filehandle reference in a normal scalar variable. Instead of using a bareword for the filehandle name, we use a scalar variable whose value is undef.

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

If the scalar already has a value, this doesn't work because Perl won't stomp on our data.

my $log_fh = 5;
open $log_fh, '>> castaways.log'
        or die "Could not open castaways.log: $!";
print $log_fh "We need more coconuts!\n";   # doesn't work

However, the Perl idiom is to do everything in one step. We can declare the variable right in the open statement. It looks funny at first, but after doing it a couple (okay, maybe several) times, you'll get used to it and like it better.

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

When we want to print to the filehandle, we use the scalar variable instead of a bareword. Notice that there is still no comma after the filehandle.

print $log_fh "We have no bananas today!\n";

That syntax might look funny to you, though, and even if it doesn't look funny to you, it might look odd to the person who has to read your code later. In Perl Best Practices, Damian Conway recommends putting braces around the filehandle portion to explicitly state what you intend. This syntax makes it look more like grep and map with inline blocks.

print {$log_fh} "We have no bananas today!\n";

Now we treat the filehandle reference just like any other scalar. We don't have to do any tricky magic to make it work.

log_message( $log_fh, 'My name is Mr. Ed' );

sub log_message {
  my $fh = shift;

  print $fh @_, "\n";
}

We can also create filehandle references from which we can read. We simply put the right thing in the second argument.

open my $fh, "castaways.log"
        or die "Could not open castaways.log: $!";

Now we use the scalar variable in place of the bareword in the line input operator. Before, we would have seen the bareword between the angle brackets:

while( <LOG_FH> ) { ... }

And now we see the scalar variable in its place.

while( <$log_fh> ) { ... }

In general, where we've seen the bareword filehandle we can substitute the scalar variable filehandle reference.

In any of these forms, when the scalar variable goes out of scope (or we assign another value to it), Perl closes the file. We don't have to explicitly close the file ourselves.


Previous
Table of Contents
Next
© 2000- NIV