[pm-h] reading a file as a string

Andy Lester andy at petdance.com
Sat May 19 22:51:24 PDT 2007


On May 20, 2007, at 12:43 AM, Russell L. Harris wrote:

>> my $file_as_string = do {
>>      open( my $fh, $filename ) or die "Can't open $filename: $!";
>>      local $/ = undef;
>>      <$fh>;
>> };
>
> I am confused by the use of "my $fh" in the open command.  By what
> mechanism is $fd assigned a value?

The "my $fh" declares a lexical scalar, and the open() assigns a  
filehandle to it.

The old way:

   open( FILEHANDLE, $filename )

The new way:

   open( my $fh, '<', $filename )

The problem with the old FILEHANDLE method is that it's a global  
variable.  It has no scope.  If call a subroutine that also operates  
on FILEHANDLE, say by closing the file, and then return, you're going  
to be sad.

Lexical filehandles let you keep filehandles within a scope, where  
they belong.  When they go out of scope, they're automatically  
closed, too.

Also, start using the 3-arg open.  The middle argument gives an  
explicit instruction on how to open the file, for input or output.

xoxo,
Andy

--
Andy Lester => andy at petdance.com => www.petdance.com => AIM:petdance






More information about the Houston mailing list