Thread Arrays mit Paaren vergleichen
(6 answers)
Opened by pktm at 2010-09-09 23:29
Ja, mit Mengenoperationen könnte man das ziemlich schön formulieren. Habe nach kurzem Googlen keine vorhandene Lib gefunden, aber man kann die Funktionalität relativ einfach nachbauen (array_diff und array_union unterscheiden sich nur minimal bei der grep-Bedingung):
Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 #!/usr/bin/perl use strict; use warnings; sub pair_hash { return $_[0][0] . ',' . $_[0][1]; } sub array_union { my ($a, $b) = @_; my %bhash = map { &pair_hash($_) => 1 } @{$b}; return grep { defined $bhash{ &pair_hash($_) } } @{$a}; } sub array_diff { my ($a, $b) = @_; my %bhash = map { &pair_hash($_) => 1 } @{$b}; return grep { !defined $bhash{ &pair_hash($_) } } @{$a}; } my @pairs_in_db = ([1,2],[1,9],[3,4],[5,6]); my @pairs_from_somewhere_else = ([1,2],[5,6],[7,18]); my @was_in_db = &array_union(\@pairs_in_db, \@pairs_from_somewhere_else); my @pairs_to_delete = &array_diff(\@pairs_in_db, \@pairs_from_somewhere_else); my @pairs_to_create = &array_diff(\@pairs_from_somewhere_else, \@pairs_in_db); foreach my $ext (@was_in_db) { printf("<%s, %s> was in db\n", @{$ext}); } foreach my $ins (@pairs_to_create) { printf("<%s, %s> has to be inserted into the databse\n", @{$ins}); } foreach my $del (@pairs_to_delete) { printf "<%s, %s> will be removed\n", @{$del}; } Gruss Stefan Last edited: 2010-09-10 08:45:11 +0200 (CEST) |