Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: list item comparison

by nitin1704 (Sexton)
on Jul 13, 2012 at 02:22 UTC ( #981535=note: print w/ replies, xml ) Need Help??


in reply to Re: list item comparison
in thread list item comparison

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;


Comment on Re^2: list item comparison
Download Code
Re^3: list item comparison
by dasgar (Deacon) on Jul 13, 2012 at 03:28 UTC
    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!

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

        That's where do blocks come in handy :-)

        knoppix@Microknoppix:~$ perl -E ' > $sayIt = 1; > do { > say q{Hello}; > say q{World}; > } if $sayIt;' Hello World knoppix@Microknoppix:~$

        I hope this is of interest.

        Cheers,

        JohnGG

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2014-12-25 18:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (162 votes), past polls