You can have as many files or file handles open as you can think up names of variables for. I would suggest not slurping entire files into memory if there is a possibility they can be very large. I would sugest using a while loop, i.e.:
use strict; use warnings; # take the files as command line arguments # @ARGV contains all arguments passed in my $first_file = shift (@ARGV); my $second_file = shift (@ARGV); # double check that the file exists # that they can be read # and that they are text unless ((-e $first_file) and (-r $first_file) and (-T $first_file) and (-e $second_file) and (-r $second_file) and (-T $second_file)) { die ("Can't open one of the files!"); } open("FIRST", "< $first_file") or die ("Can't open $first_file because $!"); open("SECOND", "< $second_file") or die ("Can't open $second_file because $!"); my $linenumber = 0; while (1) { # we can use an infinite loop because # we have a last in here... # I could have compressed everything into the # conditional () but that makes it harder # to understand what is going on my $line1 = <FIRST>; my $line2 = <SECOND>; last unless ($line1 and $line2); $linenumber++; if ($line1 eq $line2) { print "$linenumber matches on each file!"; # note we used eq # == is for numerical values # eq is for strings } } print "We processed $linenumber lines\n";
Note that in the above example I didn't use if ($line1 == $line2), but used if ($line1 eq $line2) The reason for that is that == is numerical equality and eq is string equality. Also note that you're no longer slurping up entire files -- reading them into arrays. This is important if you don't have to do it because large enough files will cause your box to gnash and grind its swap space.
Also note that if your program is called like:
% myscript.pl foo bar@ARGV will contain: ("foo", "bar"). Also note that -e followed by a filename checks if a file exists, -r followed by a filename checks if it is readable by the effective UID/GID (-R checks for readability by the real UID/GID), and -T checks if the file is a text file
Update: Thanks Limbic~Region for pointing out that you can only have as many file handles open as your system allows. According to Limbic~Region , this can be 256 on some combinations of Perl / Solaris.
In reply to Re: Reading from two files at once
by Vautrin
in thread Reading from two files at once
by sweeks
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |