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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.