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

I know this should be a simple task - but for the life of me I can not find a reference or work about it in a book. What is the trick. I have a script that is reading a flat file parsing it out and inputing records into a database. For each line processed I want to increment a counter variable and output that value to the command line, but I want it to stay on the same line overwritting itself for each print. Can someone please show me how simple and how lame I am for not figuring this one out. Thanks, Batcater.
  • Comment on Outputing a simple counter to stdout on the same line.

Replies are listed 'Best First'.
Re: Outputing a simple counter to stdout on the same line.
by FunkyMonk (Bishop) on Jul 13, 2007 at 14:39 UTC
    $| = 1; for my $i ( 1..10 ) { print $i, "\r"; sleep 1; }

    $| = 1 does the magic. It turns on autoflush on the currently selected filehandle (stdout, by default).

    The \r in print "...\r" sends the cursor back to the beginning of the line

    $| is described in perlvar

Re: Outputing a simple counter to stdout on the same line.
by rpanman (Scribe) on Jul 13, 2007 at 14:40 UTC
    This should work on *nix systems.
    $|=1; for (1..3){ print "\r$_";sleep 1; }
    You have to make sure you autoflush ($|=1), otherwise it doesn't work...
    Update: Dammit... beaten to it by FunkyMonk!
Re: Outputing a simple counter to stdout on the same line.
by ww (Archbishop) on Jul 13, 2007 at 14:39 UTC
    ...and output that value to the command line, but I want it to stay on the same line overwritting itself for each print....

    Are we to understand your question as "how do I overwrite the command line output?" If so, the book you're looking for is likely a book on your OS.

    It's very helpful to those would would try to help you, if you post (minimal, relevant) code illustrating what you've done, and provide by example or greater clarity, what you're not happy with.