Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Printing an array using while loop

by moritz (Cardinal)
on Oct 21, 2007 at 20:25 UTC ( #646303=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://646303]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2019-08-21 16:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?