in reply to Re^3: perl sort issue while going through article at perl.com
in thread perl sort issue while going through article at perl.com
I am looking to find out how many key2 are in the hash and how many key1 is in the hash and etc.. Below tutorial does not tell you how many of each key exists in the hash#!/usr/bin/perl -w use strict; use diagnostics; my $hash = { key1 => 'value1', key2 => 'value2', key3 => 'value3', key1 => 'value3', key1 => 'value33', key1 => 'value3', key2 => 'value3', key2 => 'value3', key4 => 'value3', key4 => '23232', }; #foreach (keys %{$hash}) { # print "$_ => ${$hash}{$_}\n"; #} my %hist; foreach (keys %{$hash}) { $hist{$_}++ for $_; } foreach (keys %hist) { print "$_ , $hist{$_}\n"; } print "size of hash: " , keys(%{$hash}) . "\n"; ././././perl.hash.basic.2 key2 , 1 key1 , 1 key4 , 1 key3 , 1 size of hash: 4
Now there are two passes over the list, and the situation isn't going +to get any prettier from here. What you want is basically a histogram + of the data, and you can get that with a hash: my %histogram; $histogram{$_}++ for @list; This hash associates each individual item with its count, and it only +traverses the list once. In a recent case, I was looking at a list of tags associated with vari +ous photographs. To lay out the data for display, it was useful to kn +ow how many different tags there are in the list. I could get that si +mply from the number of keys in the histogram: $unique = keys %histogram; I could also delete the duplicates and end up with a list of the uniqu +e tags: @unique = keys %histogram;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: perl sort issue while going through article at perl.com
by shmem (Chancellor) on Oct 23, 2007 at 05:51 UTC | |
|
Re^5: perl sort issue while going through article at perl.com
by convenientstore (Pilgrim) on Oct 23, 2007 at 22:14 UTC | |
by FunkyMonk (Bishop) on Oct 23, 2007 at 22:57 UTC | |
by convenientstore (Pilgrim) on Oct 24, 2007 at 00:46 UTC |