sub listprimes {
my $n = shift;
my $i = 0;
my $answer = "";
while($primes[$i] <= $n) {
$answer .= " $primes[$i]";
$i++;
}
return $answer;
}
The while-loop is stepping through all the elements of @primes and appending the element to a string while that element is less than or equal to the $n limit. When an element of @primes is encountered that is greater than the $n limit, the while-loop terminates.
Another way to step through (or "iterate over") each element of an array is with a foreach loop (which can be shortened to for in all cases). This use of a for-loop is a common Perl idiom. Inside the for- or foreach-loop, you can decide to either append the element to the string or to exit the loop. (This doesn't use push; we'll get to that presently.) Something like:
for my $element (@primes) {
if ($element <= $n) {
$answer .= " $element";
}
else {
last;
}
}
or maybe:
for my $element (@primes) {
last if $element > $n;
$answer .= " $element";
}
See the last loop control built-in function. Note that the loop exit test in the second variation is explicitly > whereas this had been only implicit before. Both of these approaches relieve you of the need to manage the $i index variable.
How could you use push in all this? (I wouldn't bother; the code now seems simple enough.) In any event, maybe:
my @in_range;
for my $element (@primes) {
last if $element > $n;
push @in_range, $element;
}
return " @in_range";
Note that the $answer variable is no longer needed.
(But see NetWallah's reply for a very neat and concise implementation of this function.) (Update: But see my caveat.)
Update: Many small wording changes and additions of afterthoughts, and $string changed to $answer everywhere.
Give a man a fish: <%-{-{-{-<
|