Your exact spec and your example program don't quite cooperate with one another, but this should get you closer:
Update: This code is buggy so I've put it in a readmore (not trying to hide that I make mistakes, after all). See Re^3: Array name with a Variable for the corrected code. The declaration of the hashes here is in the wrong scope and they weren't getting emptied properly.
use strict; use warnings; my @array1 = qw( c d e ); my @array2 = qw( e f g h ); my @array3 = qw( a b d ); my @array4 = qw( s g h j k l ); open my $out, '>', 'output' or die "Cannot open: $!\n"; foreach my $a1 ( \@array1, \@array2, \@array3, \@array4 ) { my ( %union, %intersect ) = ( (), () ); foreach my $a2 ( \@array1, \@array2, \@array3, \@array4 ) { foreach my $item1 ( @$a1 ) { foreach my $item2 ( @$a2 ) { # print "item1: $item1\nitem2: $item2\n"; $union{$item1}++; $union{$item2}++; if ( $item1 eq $item2 ) { $intersect{$item1}++; } } } my @intersect = sort keys %intersect; print $out "@intersect\n"; #prints intersecting words print $out scalar @intersect . "\n"; } } close $out or die "Error closing output; $!\n";
If you don't want the intersection of an array and itself, there's an easy way to do that with flow control for the loops. You might also want to look into Set::Scalar or other CPAN modules that have done much of the work for you.
In reply to Re: Array name with a Variable
by mr_mischief
in thread Array name with a Variable
by godevars
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |