in reply to Perl File Comparison

I would do it a little different

Obviously you probably done want to push the file into an array if they are large.

use strict; use warnings; use Data::Dumper; my $file_base = '1.TXT'; my $file_filter = '2.TXT'; open ( FILTER, "<$file_filter" ) or die "Die: Could not open $file_filter: $!"; open ( BASE, "<$file_base" ) or die "Die: Could not open $file_base: $!"; my @filterArray = <FILTER>; my @baseArray = <BASE>; close BASE; close FILTER; unless( arrayDiff( \@filterArray , \@baseArray ) ) { print "Success!"; } sub arrayDiff { my $array1 = shift(@_); my $array2 = shift(@_); my %array1_hash; my %array2_hash; # Create a hash entry for each element in @array1 for my $element ( @{$array1} ) { $array1_hash{$element} = @{$array1}; } # Same for @array2: This time, use map instead of a loop map { $array2_hash{$_} = 1 } @{$array2}; for my $entry ( @{$array2} ) { if ( not $array1_hash{$entry} ) { return 1; #Entry in @array2 but not @array1: Differ } } if ( keys %array1_hash != keys %array2_hash ) { return 1; #Arrays differ } else { return 0; #Arrays contain the same elements } }
Results
Monks>perl 1156663.pl Success!
"We can't all be happy, we can't all be rich, we can't all be lucky – and it would be so much less fun if we were. There must be the dark background to show up the bright colours." Jean Rhys (1890-1979)

Replies are listed 'Best First'.
Re^2: Perl File Comparison
by 5plit_func (Beadle) on Mar 03, 2016 at 13:31 UTC
    Hi, You have done a great job with your explanation. The code is clean well commented and I believe solves the problem. What I doubt is if he will understand references cos he is new to perl. My advice will be for him to first of all get comfortable with the basic before attempting to cracking or solve difficult task.