Monday, May 11, 2009

Reading a File in Perl

Two approaches are shown here. Reading the whole file and reading it line by line.

The whole file


sub ReadFile {
my ($filename) = @_;

open TMP,$filename or die "Couldn't open '$filename': $!";
local $/ = undef; # eat the whole file
my $text = ;
close TMP;
return $text;
}


Line by line


my $textfile = "blah.txt";

open TEXTFILE, $textfile or die("Could not open text file '" . $textfile . "': $!");
foreach $line (<TEXTFILE>) {
chomp($line); # remove the newline from $line.
# do line-by-line processing.
if($line =~ [insert some regexp here]) {
# you can now access the results of your regexp using $1,$2,...
}
}

No comments:

Labels

Blog Archive

Contributors