http://www.perlmonks.org?node_id=646303


in reply to Printing an array using while loop

my $item; while (defined($item = shift @array)){ print $item, "\n"; }

This destroys @array, though.

BTW there is no PERL, just perl (the interpreter) and Perl (the language)

Update: made 0-safe

Replies are listed 'Best First'.
Re^2: Printing an array using while loop
by Sidhekin (Priest) on Oct 21, 2007 at 20:31 UTC

    Update: made 0-safe

    But still not undef-safe. ;-)

    print shift @array while @array;

    ... which is about the silliest code I've ever written. Sheesh, what's with these arbitrary limitations? :)

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re^2: Printing an array using while loop
by Joost (Canon) on Oct 21, 2007 at 20:29 UTC
      Right, the correct solution checks @array, not the returned item.
Re^2: Printing an array using while loop
by ikegami (Pope) on Oct 22, 2007 at 05:58 UTC

    You've already been shown how to make your code work with all values including undef.

    while (@array) { my $item = shift(@array); print "$item\n"; }

    If you wanted safe code that didn't refer to the array twice, you could use splice in a list assignment.

    while (my ($item) = splice(@array, 0, 1)) { print "$item\n"; }

    The parens on the LHS of the assignment are crucial to force a list context. The result of a list assignment in list context is the number of list elements assigned (no matter if the element(s) are true or false).

Re^2: Printing an array using while loop
by naikonta (Curate) on Oct 23, 2007 at 16:23 UTC
    BTW there is no PERL, just perl (the interpreter) and Perl (the language)
    Of course there is. It's usually used as part of a course name. But the course ends up teaching something really different :-)

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Re^2: Printing an array using while loop
by Anonymous Monk on Jan 12, 2017 at 13:59 UTC
    >> BTW there is no PERL, just perl (the interpreter) and Perl (the language)

    AIUI, the reverse is true; Perl is the interpreter and perl is the language

    /pedant

      No, moritz was correct according to the FAQ.