in reply to Array name with a Variable
Don't use symbolic references. Use regular references instead.
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Array name with a Variable
by chromatic (Archbishop) on Apr 17, 2008 at 20:31 UTC | |
by mr_mischief (Monsignor) on Apr 17, 2008 at 20:38 UTC | |
by chromatic (Archbishop) on Apr 17, 2008 at 20:49 UTC | |
by mr_mischief (Monsignor) on Apr 17, 2008 at 20:59 UTC | |
Re^2: Array name with a Variable
by godevars (Initiate) on Apr 17, 2008 at 21:04 UTC | |
by mr_mischief (Monsignor) on Apr 17, 2008 at 21:30 UTC | |
by Anonymous Monk on Feb 02, 2012 at 15:39 UTC |
In Section
Seekers of Perl Wisdom