Think about Loose Coupling | |
PerlMonks |
Re: Unable to Understand grep and hash use for prime no.by 1nickt (Canon) |
on Aug 04, 2015 at 05:01 UTC ( [id://1137333]=note: print w/replies, xml ) | Need Help?? |
From the documentation on Perl grep():
So you are making a new list, @primes, from the original list, @numbers, including only those elements of @numbers for which the expression returns true. Your expression,
has two conditions. If either of those returns true for the number from @numbers currently being evaluated, the number is added to @primes. As grep goes through @numbers, it assigns each one to $_ as it is working with it. The first condition tests to see whether there is already an entry in the hash %is_prime for the current number:
If there is not, the second part of the first condition, after the and, is ignored and grep() goes on to the second condition. If the number does exist as a key in the hash,
checks to see whether additionally the value in the hash is true (ie not 0 or undef). If that first condition returns true, the second condition is ignored. If the first condition is false, the second condition calls the sub is_prime() with the number:
. . . and if the sub returns true, the second condition both adds the number to the hash:
. . . and causes the expression to return true, which adds the number to @primes. Hope this helps.
The way forward always starts with a minimal test.
In Section
Seekers of Perl Wisdom
|
|