in reply to Printing an array using while loop

I'm assuming that you mean
@array = qw(ball bat helmet)
Also, I'm assuming that this is homework.

Here's a hint: while(@array) tests the current length of the array. That means you will get an endless loop, but only if the array never changes.

You may want to take a look at perlfunc's section "Functions for real @ARRAYS"

updated: removed commas from qw() list. thanks liverpole.

Replies are listed 'Best First'.
Re^2: Printing an array using while loop
by downer (Monk) on Oct 21, 2007 at 20:52 UTC
    shouldnt this be really easy?
    my $counter = 0; while($counter <= $#array) { #do your thing $counter++; }
      shouldnt this be really easy?

      Uncountable numbers of fencepost errors in C programs argue otherwise.

Re^2: Printing an array using while loop
by Anonymous Monk on Oct 07, 2018 at 20:19 UTC
    # The solution to your problem is to put handles <> on your array: while(my $item = <@array>) { print("$item\n"); }
      put handles <> on your array: while(my $item = <@array>) { print("$item\n"); }

      Although this works in this particular case, I wouldn't recommend it: The <> actually doesn't do anything with "handles" (like <$filehandle>, which is readline), instead it's glob in disguise, and glob has several caveats. I would suggest a regular foreach, or perhaps each (Perl >= 5.12, which was not available in 2007, at the time of this thread).

      $ perl -MO=Deparse -e 'while(my $item = <@array>) { print "$item\n" }' while (defined(my $item = glob(join $", @array))) { do { use File::Glob (); print "$item\n" }; }