If you read the first list into a hash instead of an array, you can then use a hash slice with the second array to get the intersection.
#usr/bin/perl use strict; my $name_1 = q{list_1.txt}; my $name_2 = q{list_2.txt}; open my $INFILE_1, q{<}, $name_1 or die "Can't open $name_1 : $!"; open my $INFILE_2, q{<}, $name_2 or die "Can't open $name_2 : $!"; my %list_1; # changed while (my $line_1 = <$INFILE_1>){ $line_1 =~ s/\s+$//; $list_1{$line_1} = $line_1; # changed } my @list_2; while (my $line_2 = <$INFILE_2>){ $line_2 =~ s/\s+$//; push @list_2, $line_2; } close $INFILE_1; close $INFILE_2; # changed from here down my @intersection = grep { defined } @list_1{@list_2}; foreach my $line ( @intersection ) { print "$line\n"; }
This also requires that list 2 not have duplicate elements.
In reply to Re: is there a more simple way to have the intersection of two lists ?
by kyle
in thread is there a more simple way to have the intersection of two lists ?
by steph_bow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |