in reply to Re^3: Perl program - I hope I can more understand my code
in thread Perl program - I hope I can more understand my code
Here's what your instructor may be hinting at. Let's use the re-formatting of AppleFritter:
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.sub listprimes { my $n = shift; my $i = 0; my $answer = ""; while($primes[$i] <= $n) { $answer .= " $primes[$i]"; $i++; } return $answer; }
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:
or maybe:for my $element (@primes) { if ($element <= $n) { $answer .= " $element"; } else { last; } }
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.for my $element (@primes) { last if $element > $n; $answer .= " $element"; }
How could you use push in all this? (I wouldn't bother; the code now seems simple enough.) In any event, maybe:
Note that the $answer variable is no longer needed.my @in_range; for my $element (@primes) { last if $element > $n; push @in_range, $element; } return " @in_range";
(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: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Perl program - I hope I can more understand my code
by GotToBTru (Prior) on Oct 22, 2015 at 12:36 UTC | |
by AnomalousMonk (Archbishop) on Oct 22, 2015 at 22:38 UTC |