Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Problems with looping through an array

by gmax (Abbot)
on May 27, 2004 at 10:34 UTC ( #356855=note: print w/ replies, xml ) Need Help??


in reply to Problems with looping through an array

Use a hash to get a count of each unique item.

#!/usr/bin/perl -w use strict; use Data::Dumper; my @ID = (1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,4,4,4,4,4,5,5,5,5); # # count # my %items =(); $items{$_}++ for @ID; print "$_ => $items{$_}\n" for sort keys %items; # # detail # %items =(); my $count =0; push @{$items{$_}}, $count++ for @ID; print Data::Dumper->Dump([ \%items], ['items']); __END__ output: 1 => 8 2 => 6 3 => 2 4 => 5 5 => 4 $items = { '4' => [ 16, 17, 18, 19, 20 ], '1' => [ 0, 1, 2, 3, 4, 5, 6, 7 ], '3' => [ 14, 15 ], '2' => [ 8, 9, 10, 11, 12, 13 ], '5' => [ 21, 22, 23, 24 ] };

(update) Instead of Data::Dumper, you could also get your details this way:

print "$_ => (@{$items{$_}})\n" for sort keys %items ; __END__ 1 => (0 1 2 3 4 5 6 7) 2 => (8 9 10 11 12 13) 3 => (14 15) 4 => (16 17 18 19 20) 5 => (21 22 23 24)

See also Perl Idioms Explained - keys %{{map{$_=>1}@list}} in Tutorials to see how the hash mechanism works.

As for the error in your code, this node could be of help.

 _  _ _  _  
(_|| | |(_|><
 _|   


Comment on Re: Problems with looping through an array
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://356855]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (13)
As of 2014-10-22 13:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (118 votes), past polls