http://qs321.pair.com?node_id=11146511


in reply to Limit loop

foreach ( @favs[ 0 .. 24 ] ) {

Replies are listed 'Best First'.
Re^2: Limit loop
by pryrt (Abbot) on Aug 30, 2022 at 20:59 UTC
                foreach ( @favs[ 0 .. 24 ] ) {

    Since the original post said only "a few of these favorite fields have more than 25", then most of the time, that will end up with one or more undef iterations on the loop, so then undef would have to be handled specially. Maybe via next unless defined; or similar logic.

      Thanks but this didn't work. It just throws the same end of script output before header error. And YES, most of them have less than 25 favs but some do have more. Most of the time this is a non issue.
        Your script not working has nothing to do with whether or not the loop properly exits after a maximum of 25 loops.

        You need to fix your bugs before declaring that someone's solution for a small question is invalid.

        Thi spoiler contains an SSCCE that fixes (some) of your mistakes, with comments. But in brief, you didn't use strict and warnings, so you missed some of the problems; you initialized the wrong variable outside of your loop (which would have been caught by strict/warnings); and your vertical bar split had too many vertical bars, so it never split your loop variable into three variables (instead, putting the whole string in the $favtitle and leaving $favlink and $favnum as undef).

        The code below shows the same loop working for both 5 favorites in the string (showing all) and for 30 favorites in the string (showing 25 of them).


        edit: struck about the vertical bar; the eventual follow-on data shows that there really are 3 bars between fields. Sorry.

        Before the loop remove the excess elements

        splice @favs, 25; foreach (@favs){