in reply to How to compare hash value
gives the result of 2. This is because you're assigning into the hash value the result of (scalar @a). If you really want to go with a hash of lists, your code should look more likeLIAM:~$ perl push(@a, 'a'); push(@a, 'b'); $foo{stuff} = @a; print $foo{stuff} . "\n";
Instead, you probably should be using a hash of hashes, e.g.$myhash{$key1}=\@value1
This will prevent duplicate elements from messing up your set. Then, you can use sort and keys together to do the compare. Here's a subroutine that does what I think you're looking for:$myhash{$key1} = {'abd' => 1, 'bcd' => 2, ...};
Note that this code is very untested. Here's some minimal test code:sub add_set { # adds a set if it's unique, otherwise does nothing. my ($mhash, $new_hashid, @elements) = @_; my %endhash; foreach my $element (@elements) {$endhash{$element} = 1;} my @matched_keys = grep { my $truth = 1; foreach my $cand_element (keys %endhash) {$truth *= defined $mhash{$_}{$cand_element}; } } (keys %$mhash); # This only ensures that we have a subset my $magic_key; foreach my $matched_key (@matched_keys) { my $match_ok = 1; foreach my $c_elem (keys %{$mhash{$matched_key}} ) { if(! defined($endhash{$c_elem}) ) {$match_ok = 0;} } if($match_ok) {$magic_key = $matched_key;last;} } if(defined($magic_key) ) { # Our set is already in here, so just return print "Set already found, returning\n"; return; } $$mhash{$new_hashid} = \%endhash; # Otherwise, add it }
Thinking about it, Quantum::Superpositions might be a better way to do this. There also might be a fairly obvious better way to do this that I'm not seeing. Anyhow, I hope this helps.my %foo; $foo{set1} = {a=>'beta', 'c'=>'gamma'}; add_set(\%foo, "set2", 'beta','gamma'); add_set(\%foo, "set3", 'moo', 'cow'); print join("\n", keys %foo);
|
|---|