in reply to Delete from array
This is a problem I tackle daily (in Python). After I had implemented the two-way compare you mentioned, I longed for the remaining two classes of elements as well, and ended up with four classes of entries in two lists :
I looked around, but there is no module for comparing two arrays and dividing them up into the four classes in Perl (there also was nothing comparable in Python, but with Python, I'm used to writing my own stuff :-)).
So here is my algorithm of how I do this :
Work interferes, so I won't write up the implementation - watch this space for an update
Update:(untested though)
=pod extract_key takes an element from a list and returns a scalar that is +the key element. Think of MD5. =cut sub extract_key { # blindly return the item itself, stringified. return "@_"; }; sub compare_items { # plain string identity comparision $_[0] eq $_[1] }; sub compare_lists { my ($list_a, $list_b) = @_; my (%dict); my %result = ( equal => [], different => [], only_a => [], only_b => [], ); for my $item_a (@$list_a) { my $key = extract_key($item_a); $dict{$key} = [] unless exists $dict{$key}; push @$dict{$key}, $item_a; }; my @found; for my $item_b (@$list_b) { my $key = extract_key($item_b); if (exists $dict{$key}) { if (@$dict{$key}) { my $item_a = shift @$dict{$key}; push @found, [ $item_a, $item_b ]; } else { push $result{only_b}, $item_b; }; }; }; push $result{only_a}, @$dict{$key} for my $key (keys %dict); for my $pair (@found) { if (compare_items( $pair->[0], $pair->[1] )) { push @$result{equal}, $pair; } else { push @$result{different}, $pair; }; }; return %result; };
perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Delete from array
by dragonchild (Archbishop) on Aug 07, 2003 at 13:21 UTC |