Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others cooling their heels in the Monastery: (1)
    As of 2021-01-19 06:30 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      Notices?