in reply to comparing contents of the file
We strongly recommend that you use strictures (use strict; use warnings;) at the start of all the Perl you write. They give you early warning of a wide range of issues.
We also like it if you tell us up front if you are doing homework or are doing this as a learning exercise (this smells like a homework question) so that we can tailor our replies to help you learn.
Your first attempt is almost ok for small files, although the syntax is not correct and there is a problem. A syntax corrected version would look somewhat like:
use strict; use warnings; my $F1 = <<F1; name value n1 001 n2 002 n3 003 n4 004 F1 my $F2 = <<F2; name value n5 005 n2 002 n3 003 n8 008 F2 open FH1, '<', \$F1 or die "Failed to open F1: $!"; open FH2, '<', \$F2 or die "Failed to open F2: $!"; my @f1= <FH1>; my @f2= <FH2>; for my $f1Line (@f1) { for my $f2Line (@f2) { if ($f1Line eq $f2Line) { print "Same: $f1Line"; } else { print "Diff: $f1Line"; } } } close(FH1); close(FH2);
which prints:
Diff: name value Diff: name value Diff: name value Diff: name value Diff: name value Diff: n1 001 Diff: n1 001 Diff: n1 001 Diff: n1 001 Diff: n1 001 Diff: n2 002 Diff: n2 002 Same: n2 002 Diff: n2 002 Diff: n2 002 Diff: n3 003 Diff: n3 003 Diff: n3 003 Same: n3 003 Diff: n3 003 Diff: n4 004 Diff: n4 004 Diff: n4 004 Diff: n4 004 Diff: n4 004
which is not quite what you want and becomes horribly slow when the files get big.
Generally however this is a tricky problem to solve because good solutions require knowledge of the size and nature of the contents of the files. A common key to the solution involves using hashes (see perldata) to keep information about data that has been seen before.
At this point you can either play with your current code, or learn about hashes and possibly come back for more instruction.
|
|---|