in reply to Primes. Again.

Your main issue was that you were blanking out non-primes, but then using them in calculations. The empty string part of the error message was a clue. The line number was another. You may like this cleaned up version of you code that fixes that problem, suppresses the blank lines that your original code would have produced, and reduces the nesting somewhat.

use strict; use warnings; my @prime = (2); for my $i(3..100){ push @prime, $i; for(@prime){ next if ! length $_; next if int($i/$_)!=($i/$_) or $i==$_; $_=~s/$i// for @prime; } } print join "\n", grep {length $_} @prime;

Prints:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Primes. Again.
by Andrew_Levenson (Hermit) on Apr 26, 2006 at 03:24 UTC
    At the risk of being obnoxious, I must politely request:
    If you find the time, could you break down the following lines for me? They are too advanced for me to read.
    next if ! length $_;
    next if int($i/$_)!=($i/$_) or $i==$_; (I suppose I don't understand 'next')
    print join "\n", grep {length $_} @prime;

    Thanks.

      Not obnoxious at all! Healthy curiosity from a Perl newbie I'd have said.

      next is a statement used inside a loop to say "skip the rest of the loop code and start the next itteration".

      next if ! length $_;

      is a next statement that is modified by an if. It is only executed if the if condition is true.

      join concatenates the elements of a list together using the string supplied between each pair of elements.

      grep filters a list of elements and only returns the list of elements for which the condition (in {} brackets) evaluates true.

      Note that this is a very quick introduction to these concepts. I expect you will take a trawl through the tutorials section now looking for next, last, redo, join, grep, map and modifiers.

      You should look for those key words in The Camel too.


      DWIM is Perl's answer to Gödel
        I, for the life of me, could not grasp the "length $_" concept (what it was testing for each entry), so we re-wrote it in a way that worked better for our comprehension.

        use strict; use warnings; my @prime = (2); my $not_prime; for my $i(3..100){ $not_prime=0; for(@prime){ next if int($i/$_)!=($i/$_); $not_prime=1; } push @prime, $i if $not_prime!=1; } print join "\n", @prime;


        Thanks again for your help! (The next, last, and conditional-if's that you inadvertantly taught me are VERY welcomed pieces of information.)