Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
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 ( [id://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

Replies are listed 'Best First'.
Re^2: Creating hash: Key is unique string in array element, value is number of times it appears
by johngg (Canon) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://933765]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-24 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found