On Feb 28, 2004, at 11:12 AM, Stuart White wrote:

So I figured out from folks on the list, Beginning
Perl, and some print statements that
@list = (2 .. $input);

Good work.


puts the range of numbers into an array, and that if I
stringified it, then it would put the entire range
into $list[0]

That's not really accurate. What was said to that:


@list = "@list";

Creates a joined string of elements and replaces the list with that one item. It's perfectly reasonable to stringify an array, without altering the array's contents:

print "@list\n";

Now that I've figured that bit out, I went on to
remove all the even numbers from the list.  I got that
done with this:
foreach (@list)
{
 if ($_ % 2 != 0)

That can just be if ($_ % 2), if you prefer. Zero is Perl's idea of false and it considers anything else true, so it'll work the same.


 {
  unshift(@primelist, $_);
  @primelist\n";   

The above line is not a valid Perl statement.


 }
}

As a shortcut, you can weed out evens when you make the list, if you like:


@list = map { $_ % 2 ? $_ : (); } 3..$input;

But that's probably not as pretty.

Now what I'd like to do to test whether or not I have
a prime number is to get at each element in
@primelist, and use the modulus operator on each
element against each element in @list.  For example:
$primelist[0] % $list[0]
$primelist[0] % $list[1]
$primelist[0] % $list[2]
$primelist[1] % $list[0]
$primelist[1] % $list[1]
$primelist[1] % $list[2]
$primelist[2] % $list[0]
$primelist[2] % $list[1]
$primelist[2] % $list[2]        

and if the result doesn't equal 0 for every test
except for against itself, then I want to unshift it
onto @primelist.

I thought I'd do this with nested foreach loops, but
that didn't seem to work.  Any ideas?

Define "didn't seem to work"? On second thought, just post that nested foreach and let us help you fix it.


James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to