in reply to Newbie Question on pushing Arrays
A bit of advice every newbie gets: put use strict as the first line of code in your script and add -w to the #! line *always* (the latter can be done away with after you've finished developing and testing the code). Doing so will force you to declare your variables and think hard about the scope of your variables (and catch typos -- $zahl is undeclared in this code). Basically, this will force you to declare your variables before you use them (use the my operator, which is documented in perldoc -f my)
One minor problem here is that $limit is, as written, going to contain the newline the user has to enter. Use chomp $limit; on the next line to remove that newline.
Now, onto the logic of your loop. I think it's more naturally written as a for loop, with 3 as the lower bound (you already know 2 is prime, after all) and $limit as the upper bound, incrementing by one each time. That way you don't have to fiddle with incrementing $number on both branches (whether it's prime or not). The code for that loop then looks like this:
for (my $number = 3; $number < $limit; $number++) { #stuff }
I like your use of a flag, keep that! But maybe rename it, like $isprime, which is more descriptive =)
As for the inner loop, you want to break out of it once you've found a member of @primes that evenly divides $number ... so use the last operator to do that. I'm not sure the array's getting mixed up , but the way you do this loop, combined with your print statements might make it look that way (54, e.g is divisible by both 2 and 3, so it will get printed twice).
(see perldoc -f last on your system's documentation to get a handle on how to use last).
HTH, and good luck.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Newbie Question on pushing Arrays
by m_heimburger (Initiate) on May 04, 2001 at 20:43 UTC | |
by chipmunk (Parson) on May 04, 2001 at 20:54 UTC | |
by buckaduck (Chaplain) on May 04, 2001 at 21:00 UTC | |
by m_heimburger (Initiate) on May 04, 2001 at 21:05 UTC |