View Full Version : help with Perl hashing please
vutien
03-11-2005, 10:25 PM
hi,
i have two arrays: @old=(0,1,2) and @new=(0,1,2,3,4)
i need to store the difference betweek the old and new arrays, so i want @diff=(3,4)
so far, this is my code but it does not work. can you tell me why or let me know a better way to do this?
sub diff{
foreach $id (@new)
{
unless (grep / $id$ /, @old) #unless it is not in old
{
push @diff, $id; #@diff=(3,4)
}
}
return @diff;
}
many thanks,
T
mlseim
03-12-2005, 12:17 AM
If your server has the module: use Array::Compare;
see this link:
http://search.cpan.org/~davecross/Array-Compare-.11/lib/Array/Compare.pm
=======================================================
Otherwise, here's an example I found on the internet (using no modules):
=======================================================
#!/usr/bin/perl
#Example from http://www.perlmonks.org/index.pl?node_id=2461
print "Content-type: text/html\n\n";
my @simpsons=("homer","bart","marge","maggie","lisa");
my @females=("lisa","marge","maggie","maude");
my %simpsons=map{$_ =>1} @simpsons;
my %females=map{$_=>1} @females;
# the intersection of @females and @simpsons:
my @female_simpsons = grep( $simpsons{$_}, @females );
# proof it works
print "<ul>The female names that are the same in both arrays (intersection)</ul><br>\n";
print "Female Simpson:\t$_ <br>\n" foreach (@female_simpsons);
# the difference of @females and @simpsons
my @male_simpsons=grep(!defined $females{$_}, @simpsons);
# proof it works
print "<br><br><ul>The differences between both arrays</ul><br>\n";
print "Male Simpson:\t$_ <br>\n" foreach (@male_simpsons);
my %union = ();
# the union of @females and @simpsons
foreach(@females,@simpsons){
$union{$_}=1;
}
my @union2 = keys %union;
# or just do this
# my @union = (@females, @simpsons);
#
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.