Friday 15 June 2012

perl - Check if key exists in hash using value from another hash as hash name -



perl - Check if key exists in hash using value from another hash as hash name -

i'm getting variable $breed in callback , i'm checking if i've seen before, , if haven't, storing in %hash doing following:

if (exists $hash{$breed}) { #exists } else { #add $hash{$breed}; }

now, since maintain track of these unique $breeds in separate hashes, made hash maintain new hash names

%hashnames =(cats => 'cathash', dogs => 'doghash'); %cathash = (); %doghash = ();

since i'm getting $species callback well, know can lookup right hash should adding $breed doing:

$hashnames {$species}

i think next okay, not:

if (exists ${$hashnames {$species}}{$breed}){ #exists }else{ #add ${$hashnames {$species}}{$breed}; }

in reality, there hundreds of species , breeds. possible? maybe i'm going wrong? thanks.

you can hash of hashes:

i not sure how getting data, here possible example:

my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'], ['cats', 'persian cat'], ['dogs', 'german shepherd']); #generating info (%cats, %dogs); %species = ('cats' => \%cats, 'dogs' => \%dogs); $specie_breed(@lol) { ($s, $b) = @{$specie_breed}; $species{$s}->{$b}++; } print dumper \%species;

result:

$var1 = { 'cats' => { 'persian cat' => 2 }, 'dogs' => { 'german shepherd' => 1, 'border collie' => 1 } };

here illustration using arrays in hash skipping:

my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'], ['cats', 'persian cat'], ['dogs', 'german shepherd'], ['cats', 'siamese']); #generating info (@cats, @dogs); %species = ('cats' => \@cats, 'dogs' => \@dogs); $specie_breed(@lol) { ($s, $b) = @{$specie_breed}; if(! grep(/$b/, @{$species{$s}})) { force @{$species{$s}}, $b; } } print dumper \%species;

result:

$var1 = { 'dogs' => [ 'border collie', 'german shepherd' ], 'cats' => [ 'persian cat', #only adds 1 time 'siamese' ] };

perl hash hashmap exists

No comments:

Post a Comment