Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: list item comparison

by dasgar (Deacon)
on Jul 12, 2012 at 21:58 UTC ( #981512=note: print w/ replies, xml ) Need Help??


in reply to list item comparison

Where's your code that you have tried?

I'll be nice share some code that should get you started. I'll leave it to you to figure out how to bundle it in a subroutine, how to pass data into and out of it, and any other modifications you need to meet your needs.

use strict; use warnings; my (@list) = (1,1,2,3,4,4,4,5,6,7,7,8,9,10); my %check; foreach my $item (@list) { if (exists $check{$item}) {$check{$item}++;} else {$check{$item} = 1;} } foreach my $key (keys %check) { my $count = $check{$key}; if ($count > 1) { print "$key was in the list $count times.\n"; } }


Comment on Re: list item comparison
Download Code
Re^2: list item comparison
by nitin1704 (Sexton) on Jul 13, 2012 at 02:22 UTC

    There is no need to check if the $item exists in the hash. When you increment a the value for a key which doesn't exist, the key springs into existence. So lines 8-11 can be replaced by:

    $check{$_}++ for @list;
      When you increment a the value for a key which doesn't exist, the key springs into existence.

      Didn't know that. Thanks for the info.

      However, I'd like to point out one thing. Back when I was first learning Perl, your one line for loop code would have had me thoroughly confused. Based on the original question asked by the OP, I was left with the impression that the OP was a bit of a beginner. In that case, my foreach loop would probably be somewhat easier to follow along and understand.

      Plus, I personally find that my foreach loop more closely matches how I would think through the task, which in turn would mean easier code for me to personally maintain. Just a personal preference.

      Anyways, thanks for the tip!

        Yes, it's easier to understand the way you presented it. The one line syntax (statement modifier form) is fairly common in Perl though, and it's great if beginners can pick it up. @OP: This syntax can be used with both loops and conditions. E.g:

        if($cond){ doSomething(); }

        can be replaced by:

        doSomething() if $cond;

        The only catch is that you can execute only one statement per iteration/condition with this syntax. Happy coding!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2014-12-17 23:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (40 votes), past polls