in reply to Re^4: Perl program - I hope I can more understand my code
in thread Perl program - I hope I can more understand my code
You're on the right path, but you're not using foreach and push the way they're intended to yet. If you've not done so yet, I'd suggest starting by reading both Compound Statements (for foreach) and push (for, well, push).
However, I realize that these documents are aimed at people who are already familiar with programming in principle, so here's some extra hints. First of all, let's deal with foreach the way it's intended to be. You have:
foreach $x ($primes[$i]<=$n) {
But what does foreach actually do? It iterates through a list of values, assigning each to the loop variable in order and then executing the loop body. Your code, however, does not have a list of values, it has a boolean condition ($primes[$i]<=$n) that might evaluate to true or false. That's good for a while loop, but won't do for a foreach loop.
Think back to what you're trying to achieve: you want to list primes up to a certain maximum. So what list should you iterate through? The prime numbers, which you already have in @primes.
Now, the loop body:
push $x{$n}
What does push do? It appends a new element to an array, at the end. As such you'll need two things: an array to append to, and an element to append. Again, think about what you want to obtain: a list of primes that meet a certain condition. So you'll need a new array that will hold this list; and the element you'll need to push is the prime currently being considered, if it does indeed meet the condition.
I don't want to solve your entire homework for you, but here's some pseudo-code to show you what you need to do:
foreach loop to iterate through the primes { if prime number currently being considered does not exceed $n { push it to the result list. } }
I hope this'll help.
Two more notes: first, you will have to declare your result list before using it, using my, just like all the other variables. And second, you will also have to declare your loop variable ($x in your code), though Perl allows you to do this in the loop (foreach my $x (...) {) .
|
|---|