in reply to counting occurrence of an element in a hash
G'day JusaEngineer,
Welcome to the Monastery.
You can collate all the information you want in a single, new hash by iterating the values of %hash and transferring information to the new hash.
In the script below, I've given all of the Descriptions unique values: you can now tell all three "A Description of this button On/Off" apart (ditto for the two with "Momentary").
#!/usr/bin/env perl use strict; use warnings; my %hash = ( 'ScreenName1.Description1' => { 'ScreenName' => 'A', 'Description' => 'Desc1', 'Type' => 'On/Off' }, 'ScreenName2.Description2' => { 'ScreenName' => 'B', 'Description' => 'Desc2', 'Type' => 'Momentary' }, 'ScreenName3.Description3' => { 'ScreenName' => 'A', 'Description' => 'Desc3', 'Type' => 'Momentary' }, 'ScreenName4.Description4' => { 'ScreenName' => 'A', 'Description' => 'Desc4', 'Type' => 'On/Off' }, 'ScreenName5.Description5' => { 'ScreenName' => 'B', 'Description' => 'Desc5', 'Type' => 'On/Off' }, ); my %parsed; for (values %hash) { push @{$parsed{$_->{ScreenName}}}, join ' ', @{$_}{qw{Description Type}}; } print "*** Counts ***\n"; print "$_ - ", 0+@{$parsed{$_}}, "\n" for keys %parsed; print "\n*** New hash (\%parsed) ***\n"; use Data::Dump; dd \%parsed;
Output from a sample run:
*** Counts *** A - 3 B - 2 *** New hash (%parsed) *** { A => ["Desc1 On/Off", "Desc3 Momentary", "Desc4 On/Off"], B => ["Desc2 Momentary", "Desc5 On/Off"], }
Note that hashes are unordered. Here's the output from another sample run:
*** Counts *** B - 2 A - 3 *** New hash (%parsed) *** { A => ["Desc3 Momentary", "Desc1 On/Off", "Desc4 On/Off"], B => ["Desc5 On/Off", "Desc2 Momentary"], }
Depending on how you want to use the data, you may need to use sort in one of more places. For future reference, please note that if you specify requirements you'll generally get better answers: all I have to work with is "something like" for part one, and no information at all for part two.
See also: Data::Dump.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: counting occurrence of an element in a hash
by JusaEngineer (Novice) on Jun 07, 2021 at 17:47 UTC |