[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Read entire file?



on 12/27/2000 11:00 AM, Jim Correia at correia@barebones.com wrote:

> So I'm a c programmer, and my perl book is at the office.
> 
> What is the best (fastest, clearest code) to read an entire file into a
> variable?  I want to preserve whatever line endings were in the original
> file so I don't want to read it by lines.  Right now I am reading by
> chunks because I can't seem to find a function that will return the size
> in bytes of the file on disk...
> 
> Thanks,
> Jim

Couple of ways 

Usually if I'm going to slurp a file into Memory, I do it like this:

use File::Spec;
my $filename = 
  File::Spec->catfile( File::Spec->curdir(), 'mysubdir', 'filename.txt');

open INPUT_FILE, "<$filename" or die "Cannot Open $filename -- $!";
# (this way, of course, chomps the line endings; obviously)
chomp(my @data = <INPUT_FILE>); #need those parens!
close INPUT_FILE;

but you could do it the same (similar actually) way with a scalar and have
it in a scalar instead of an array.

also look in the pod documentation for "Paragraph Mode", where you change
one of the global Perl variables to slurp the file in, as paragraphs instead
of as lines. 


also look in 
    perldoc perlfunc

for the -s switch and the stat() function.

this will illustrate:

#!perl -w
use strict;
use File::Spec;
my $filetest = File::Spec->catfile( File::Spec->curdir(), 'testfile.txt');
my $slurp = '';
my $chomp = '';

# bear in mind that this is the size of the DATA FORK
# (as near as I can tell.. NOT the size of the file on disk)
my $size = -s $filetest;

print "File $filetest, has an actual size -> $size\n";

# you'll see in the stat() description how to assign these directly
# $dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
# $size, $atime, $mtime, $ctime, $blksize, $blocks

my (@data) = stat($filetest);

print "Stat reports size:$data[7], blksize: $data[11], and blocks:
$data[12]\n";

print "let's measure it\n\n";

open INFILE, "<$filetest" or die "Cannot open $filetest -- $!\n";
while (<INFILE>) {
  $slurp .= $_;
  chomp($chomp .= $_);
}
close INFILE;

print "slurp string length is: ", length($slurp), "\n";
print "chomp string length is: ", length($chomp), "\n";

open INFILE, "<$filetest" or die "Cannot open $filetest -- $!\n";
chomp(my @data2 = <INFILE>);
close INFILE;

print "chomped last array index is ", $#data2, "\n";

exit 0;


as the files get larger though, it's much more sensible to iterate over them
in a while (<FILE>) {# do something} block. (this last part takes several
seconds to process though even for a 232K text file (which I had handy) ...
the -s test was a blink of an eye.


-- 
Scott R. Godin            | e-mail : mactech@webdragon.net
Laughing Dragon Services  |    web : http://www.webdragon.net/



# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org