Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: list item comparison

by dasgar (Priest)
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"; } }

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://981512]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2018-05-24 04:57 GMT
Find Nodes?
    Voting Booth?