Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Occurence List

by Hopfi (Novice)
on Oct 10, 2012 at 17:45 UTC ( #998273=perlquestion: print w/ replies, xml ) Need Help??
Hopfi has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks! I was wondering if there is a way in perl to make a list which counts each occurence of a value. I want to use it to make a picture encrypter. So it should make a color occurence list like this:
ID Occurence 255 625 212 365 220 186 219 135 169 132 227 116 213 115 234 21 205 18 184 15
Any idea how this could be done? Cheers

Comment on Occurence List
Download Code
Re: Occurence List
by aitap (Chaplain) on Oct 10, 2012 at 17:55 UTC
    Use a hash:
    use Data::Dumper; my @list = qw/ 1 1 1 234 234 3 5 5 2 7 6 3 6 8 4 /; my %count; $count{$_}++ foreach @list; print Dumper \%count; __END__ $VAR1 = { '6' => 2, '3' => 2, '234' => 2, '7' => 1, '2' => 1, '8' => 1, '4' => 1, '1' => 3, '5' => 2 };
    Sorry if my advice was wrong.
Re: Occurence List
by Anonymous Monk on Oct 10, 2012 at 21:27 UTC
    In the above posting, notice how the mere mention of a hash-key causes it to magically appear, with the initial value of zero, so that it can be "++" incremented to the value of one. This bit of perl-mojo is called "autovivification." Otherwise known as "do the right thing quietly and with a minimum of fuss."

      In the above posting, notice how the mere mention of a hash-key causes it to magically appear, with the initial value of zero, so that it can be "++" incremented to the value of one. This bit of perl-mojo is called "autovivification." Otherwise known as "do the right thing quietly and with a minimum of fuss."

      No , that is not autovivification . Just like this is not autovivification

      $foo++; $bar[$_]++;

        However, when you

        use strict;

        writing

        $foo++;

        will cause perl to complain (if you have not declared (and thus created) $foo before),
        while writing

        $bar[396]

        will cause no complaints, even if you never used this index before(or a higher one), or never told Perl how big @bar should be. You will have to declare @bar, of course. So these two examples are not comparable. And I believe the second example actually is where we see autovivication at work.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-04-23 22:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (556 votes), past polls