On 09/29/2006 01:28 PM, Charles K. Clarkson wrote:
Derek B. Smith wrote:

: ## Below is better pratice ##
: : sub getfile {
:  my $filename = shift;
:  open F, "< $filename" or die "open failed  $!"
:  my $contents;
:  { local $/ = undef;  # Read entire file at once
:    $contents = <F>;   # Return file as one line
:  }
:  close F;
:  return $contents;
: }
: : : I read an excerpt from
: http://perl.plover.com/local.html#2_Localized_Filehandles

    Curiously, you do not actually localize the file
handle in getfile().

: and was wondering if this holds true regarding
: localizing $/ and setting it to undef in Perl 5.8.x?

    If you do not localize the $/ operator then you will
change it for the rest of the script. That might be a
problem for other I/O operations which fail to set it.

    In 5.8.x this function might better be written like
this, but I lack the experience to call it a best
practice.

sub slurp_file {

    # open file for read or die
    my $file = shift;
    open my $fh, '<', $file or die qq(Cannot open "$file": $!);

    # slurp file
    local $/ = undef;

    # return file as scalar
    return <$fh>;
}


HTH,

Charles K. Clarkson

Uri Guttman has already written File::Slurp:

my $slurped = read_file 'mylogfile.log'

I use this module quite frequently. Thanks Uri.


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to