Perl

Perl is the workhorse of the cgi-bin world. In fact ".cgi" is recognized by most systems as a suffix for Perl programs. On Linux systems, one can make Perl files executable, and insert a #! line at the beginning to invoke the Perl interpreter, as in the sample code. This also works on the WIN32 Apache server.

The main attraction of Perl is its ability to do pattern-matching, which is much too complicated to be illustrated in the sample program.

On many servers, it is necessary to put your Perl scripts into the cgi-bin directory (or its equivalent), but many servers are being reconfigured to accept Perl scripts in any directory. Because of this, the .pl suffix on the source code has been disabled by adding a .txt after it.

This code compiles and runs on the WIN32 version of ActivePerl. It must be run from the command line as below. It will not run from cgi-bin. Note that the code does not require an enclosing function like C++ code.

perl SieveE.pl


#!/usr/local/bin/perl


# //////////////////////////////////////////////////////////


# // Name: Peter M. Maurer


# // Program: Sieve of Eratosthenes


# // Due: Never


# // Language: Perl


# //////////////////////////////////////////////////////////



# define the sieve data structure


for ($i=0 ; $i<1000 ; $i++)


{


# everything is potentially prime until proven otherwise


push(@Candidates,1);


}


# Neither 1 nor 0 is prime, so flag them off


$Candidates[0] = 0;


$Candidates[1] = 0;


# start the sieve with the integer 0


$i = 0;


while ($i<1000)


{


# advance to the next un-crossed out number.


# this number must be a prime


while ($i<1000 && $Candidates[$i] == 0)


{


$i++;


}


# insure against running off the end of the data structure


if ($i<1000)


{


# cross out all multiples of the prime, starting with 2*p.


for ($j=2 ; $j*$i < 1000 ; $j++)


{


$Candidates[$j*$i] = 0;


}


# advance to the next candidate


$i++;


}


}


# all uncrossed-out numbers are prime (and only those numbers)


# print all primes


for ($i=0 ; $i<1000 ; $i++)


{


if ($Candidates[$i] != 0)


{


print $i," is prime\n";


}


}

Click Here for the actual code.