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

Re: Creating hash: Key is unique string in array element, value is number of times it appears

by spazm (Monk)
on Oct 26, 2011 at 01:14 UTC ( #933765=note: print w/ replies, xml ) Need Help??


in reply to Creating hash: Key is unique string in array element, value is number of times it appears

In perl, explicit code like this is not necessary as it would be in something more verbose like java or python. Perl has a concept of autovivification, where new values burst into being when needed. Also, ++ on a false value will return 1.

In the case where $hit[2] is not a key in %genus, requesting the key will create a corresponding value of undef. Incrementing this value will return 1.

so this snippet:

#old snippet if (exists ( $genus {$hit[2]})) { $genus{$hit[2]}++; } else{ $genus{$hit[2]} = 1; }
can be reduced to this snippet:
#new snippet $genus{ $hit[2] }++

Example:

%genus = { } ; #genus is empty $genus{ foo }; #requests foo entry, and throws away. #genus is now { foo => undef } $genus{ foo } ++; # genus is now { foo => 1 }
http://en.wikipedia.org/wiki/Autovivification


Comment on Re: Creating hash: Key is unique string in array element, value is number of times it appears
Select or Download Code
Re^2: Creating hash: Key is unique string in array element, value is number of times it appears
by johngg (Abbot) on Oct 26, 2011 at 11:06 UTC
    %genus = { } ; #genus is empty

    Let's try that!

    knoppix@Microknoppix:~$ perl -Mstrict -wE 'my %genus = {};' Reference found where even-sized list expected at -e line 1. knoppix@Microknoppix:~$

    You probably meant to use parentheses rather than curly braces, which construct a reference to an anonymous hash.

    knoppix@Microknoppix:~$ perl -Mstrict -wE 'my %genus = ();' knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

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

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (141 votes), past polls