Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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.

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

In reply to Re: Problems with looping through an array by gmax
in thread Problems with looping through an array by tcox

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2022-11-28 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?