Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Unable to Understand grep and hash use for prime no.

by sundialsvc4 (Abbot)
on Aug 04, 2015 at 11:29 UTC ( #1137351=note: print w/replies, xml ) Need Help??


in reply to Unable to Understand grep and hash use for prime no.

(Sigh...)

This sort of thing is what is (un-)affectionately known as “Perl golf.”   The programmer used grep because s/he thought it was “more efficient,” and then used or instead of an if-statement because, when using grep, he had to.

And, if that programmer were a “lone wolf,” not part of a team, this sort of coding might be quasi-okay.   Twenty-five years ago, it was necessary.   Today, we have microprocessors that do hundreds of millions of ops per second, but programmers are as expensive as they always were.   Please, today, just be clear.

If anyone would not immediately understand the use of grep and hashes to calculate prime numbers (and, who would?), please don’t code it that way (anymore).

  • Comment on Re: Unable to Understand grep and hash use for prime no.

Replies are listed 'Best First'.
Re^2: Unable to Understand grep and hash use for prime no.
by Anonymous Monk on Aug 04, 2015 at 12:01 UTC
    ... used or instead of an if-statement because, when using grep, he had to.

    No, s/he didn't "have" to.

    print "$_\n" for grep { if ($_%2) {$a=1} else {$a=0} $a } 1..10;

    Yes, it's uglier, but possible.

Re^2: Unable to Understand grep and hash use for prime no.
by 1nickt (Abbot) on Aug 04, 2015 at 15:21 UTC

    The OP does not use grep and hashes to calculate prime numbers. It uses a subroutine called is_prime(), which is not included in the posted code.

    Could you post your version, so we can learn from it?


    The way forward always starts with a minimal test.

      It looks like it is from "Beginning Perl" by Curtis Poe. Page 300 has the whole program, page 301 discusses is_prime() which is non-optimized trial division (checks divisibility by all integers up to sqrt(n)). Page 302 discusses the code in question which is introducing using a hash to cache the result.

      In particular, the test suite includes duplicates in its list. That's why the hash is used.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2019-07-15 18:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?