The idea is to loop through the original array. For each
element, either look up or add that element as a key into
a hash, and increments that key's value by one. Since Perl's
hashes use autovivification, when we try to look up a
non-existing key in a hash, that key will be added.
$hash{$_}++ for @array;
is a very common Perl idiom. If we are processing the
element 'APPLE' and it is not in the hash, a new key will
be added to the hash, and that key's value (currently
undef) will be incremented by 1 ... yielding 1. Later,
if we encounter 'APPLE' again, when we try to look up
'APPLE' it exists this time and the value returned is 1.
Add 1 to that and now we have 2 apples.
Remember, Data::Dumper is your friend! Try this
out:
use strict;
use warnings;
use Data::Dumper;
my @fruit = qw(
MANGO APPLE GRAPES MANGO MANGO MANGO
MANGO APPLES APPLES BANANA CORN APPLES
);
my %fruit;
$fruit{$_}++ for @fruit;
print Dumper \@fruit;
print Dumper \%fruit;
-
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.
|