Reputation: 2779
Whenever I want Perl to read the whole file I put undef $/
before reading the file. I tried to find more information about the variable $/
but without success.
What I need to do is to write a script in Perl that first reads the whole file to a variable and then read another file line by line. How could this be done?
Upvotes: 0
Views: 726
Reputation: 389
Here's another way to do it without directly using $/.
You can use File::Slurp's read_file to read the first file and store its data in memory.
my $text = read_file('filename');
my $bin = read_file('filename' { binmode => ':raw' });
my @lines = read_file('filename');
my $lines = read_file('filename', array_ref => 1);
And, the simplest reading method to read the second file line by line.
open(my $fh, '<', 'input.txt');
while (my $line = <$fh>) {
...
}
close $fh;
Upvotes: 2
Reputation: 6437
You can try opening and reading the first file in a local scope, and then limit the setting of $/
to that scope.
my $firstfile;
{
open my $fh, '<', $file or die;
local $/ = undef;
$firstfile = <$fh>;
close $fh;
}
# continue with $/ still set
Link:
http://perlmaven.com/slurp (section: localize the change)
Either that, or save the value of $/
to another variable before setting it to undef
, and then reset it after reading the first file.
If you don't want to use $/
, look into File::Slurp
. There is a section on using it in the link I provided.
Upvotes: 2