We could save typing and electrons:
use Math::Prime::Util qw/forprimes/; forprimes { say } 1000; # optionally takes range a,b
OK, it's cheating using modules. But it's easy, and it also uses a segmented sieve so should be efficient even with large values (e.g. list the primes between 10**18 and 10**18+100000), and works with bigints too.

Some Python ways to do this, all of which are *much* faster than the OP code when we want anything more than tiny values like 1000. There are probably even better ways.

Using sympy. Much slower than the Perl module:

from sympy import sieve for i in sieve.primerange(2,1000): print i

using gmpy2 (only ~2x slower than the Perl module):

import gmpy2 n = 2 while n <= 1000: print n n = gmpy2.next_prime(n)

Or some Python by hand that is very fast:

from math import sqrt, ceil def rwh_primes(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-a +ll-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True] * (n/3) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1 +) sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*( +i&1))/6-1)/k+1) sieve[n/3-correction] = False # If you want the count: return 2 + sum(sieve) return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve +[i]] for i in rwh_primes(1000): print i

In reply to Re^2: Perl vs. Python for prime numbers by danaj
in thread Perl vs. Python for prime numbers by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.