cutlass2006 has asked for the wisdom of the Perl Monks concerning the following question:

Dear monkists,

I note here that the concept of an automated counter variable in looping structures have been discussed before.

My question is why does this output the current loop count ?

for (1..10){
print
}

could this not be subverted as a loop counter ? tia.

update: slapping forehead: thanks....

Replies are listed 'Best First'.
Re: perl loop counter
by Fletch (Bishop) on Jul 18, 2008 at 15:31 UTC

    Because unless otherwise specified a foreach loop (which can also be spelled for as you've done) uses the usual default variable $_, and likewise if not given an explicit argument print prints the contents of said default variable.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: perl loop counter
by zentara (Cardinal) on Jul 18, 2008 at 15:38 UTC
    Additionally, you will probably be suffering from buffering. You need to put
    $|++;
    at the top of your script, so it will print immediately.

    If you put a newline "\n" in your print statement, it will print immediately in your loop; but with no newline, you won't get a print until 2k is ready to print, and it will all come out in 2k chunks.


    I'm not really a human, but I play one on earth CandyGram for Mongo
      Only if you're printing to a file. If STDOUT is connected to a terminal (as it is most of the time) it won't be buffered.

      Update: I must be drinking the stupid juice today. Ttys are line-buffered, duh.

        ...it won't be buffered

        Actually, STDOUT is line buffered by default when connected to a tty, i.e. - as zentara said - output will be written either upon encountering a newline, or when the buffer has filled up (or when the program terminates, and the buffer gets flushed).

        Try playing with something like

        for (1..3000){ print "$_ "; sleep 5 unless $_ % 1000; }
        Are you sure? On my linux xterm, this prints out in roughly 2k chunks.
        #!/usr/bin/perl for (1..6000){ print $_; select (undef,undef,undef,.001); #small delay to see buffering effects }

        I'm not really a human, but I play one on earth CandyGram for Mongo