I need to track where I currently am, and therefore, I would like the program to spit out the current iteration of the loop.

In Windows, "\r" can sometimes be useful when tracking the progress of a script. It's a bit like "\n", except "\n" moves to the left edge of the next line, whereas "\r" moves to the left edge of the current line.

The following script prints 1 to 5 and a string on the same line of output.

I normally put the "\r" at the start of the output. That way if the script dies or outputs something it will not overwrite the progress info. Also, if the output strings are of different sizes, you'll need to output some spaces at the end to overwrite the previous output string.

('Cmd' windows and their buffers can be made wider, if needed, by adjusting the "Screen Buffer Size" and "Window Size" in the "Layout" tab of the window's properties. Right-click on the window's title bar, then select "Properties".)
use strict; use warnings; $| = 1; # enable auto-flush foreach my $i ( 1 .. 5 ) { my $output = '*' x (50 - 10*$i); print "\r$i : $output", " "x20; sleep 1; } print "\n";
Output. NB Each line of output is printed on the same line of the 'Cmd' window.
1 : **************************************** 2 : ****************************** 3 : ******************** 4 : ********** 5 :

In reply to Re: Dynamically printing out iteration number from foreach loop by zork42
in thread Dynamically printing out iteration number from foreach loop by hyu968

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.