Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Easier Way?

by abitkin (Monk)
on Aug 28, 2002 at 21:25 UTC ( #193583=perlquestion: print w/replies, xml ) Need Help??

abitkin has asked for the wisdom of the Perl Monks concerning the following question:

Now, I know one way of doing this, but I would like to see if there is an easier way.

I have some code such that:
my %hash2; for my $key (sort {$hash1{$b} <=> $hash1{$a}} keys %hash1){ if (exists($hash2{$hash1{$key}})){ $hash2{$hash1{$key}}++; } else { $hash2{$hash1{$key}}=1; } }

Like I said, I can do it myself, just wondering is there was a easier way (easier being less lines/faster.) I know I loose the key that was put into my %hash1, but that's okay, becuase at this point I no longer need it.

Replies are listed 'Best First'.
Re: Easier Way?
by Arien (Pilgrim) on Aug 28, 2002 at 21:46 UTC

    Counting the number of times a value appears in your hash doesn't have to be more complicated than this:

    my %hash2; $hash2{$_}++ for values %hash1;

    — Arien

Re: Easier Way?
by Aristotle (Chancellor) on Aug 28, 2002 at 21:54 UTC
    Your if case isn't necessary, if you increment an nonexistant hash element it is autocreated for you. Also, the sort is superfluous since the order in which you look at your keys makes no difference to their count. And lastly, as has been pointed out, since you don't use the keys for anything else than to access the values, just use values rather than keys. For code, see Arien's post.

    Makeshifts last the longest.

      Wow.

      Very nice, this gives me a little insight into perl that I had missed.
      Thanks so much.
        My pleasure. :-)

        Makeshifts last the longest.

Re: Easier Way?
by FoxtrotUniform (Prior) on Aug 28, 2002 at 21:30 UTC

    Hmm. values?

    my %hash2; for my $val (sort values %hash2) { if(exists $hash2{$val}) { $hash2{$val}++; } else { $hash2{$val} = 1; } }

    Not much shorter, but a bit easier to read....

    --
    F o x t r o t U n i f o r m
    Found a typo in this node? /msg me
    The hell with paco, vote for Erudil!

      In fact, the sort and the if test are unnecessary, so we can further reduce the code to this:
      my %hash2; $hash2{$_}++ for values %hash1;

      -- Mike

      --
      just,my${.02}

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2020-05-31 23:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (177 votes). Check out past polls.

    Notices?