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

I read a post that was previously asked in this forum on how to write over text using the \r metacharacter. It seems to be behaving poorly in one case I am working on.

I am using opendir(DIR, "$directory")
to open a directory of directories, and then opendir(SUBDIR, "$directory/$subdir") to read through the subdirectories. Each subdirectory has some number of files I am interested in. (in this case, they are dna sequences, and I want to know their lengths).

I can get the subdirectory name, the number of files checked in that directory, the total number checked across all subdirectories, and some other data, just fine. The problem comes in displaying it in a dynamic fashion.
If $library is the subdirectory name, $library_sequence_count is the number of sequences processed in $library, and $project_sequence_count is the total number of sequences read, then I use the statement:
print STDERR "\t\t\t\t\r\t$library\t$library_sequence_count\t$project_sequence_count\r";
to display this as it goes. This works fine - until I run into libraries with large numbers (say, 10,000+) of sequences.

When a large library passes by, the last digit of its count remains in the second field as the new libraries come and start writing. (this is why I tried the large string of tabs followed by a \r before actually writing). I can't seem to figure out why I can't get rid of this extra digit that doesn't actually belong to $library_sequence_count.

Any thoughts would be most appreciated...

Replies are listed 'Best First'.
Re: Oddity with \r printing
by tachyon (Chancellor) on Oct 19, 2004 at 21:56 UTC

    As noted \r is a carriage return. You then have to overwrite the content of the line. printf allows you to ensure all lines are 'the same width' so overwite the previous content completetely. The Curses library allows you to manipulate a terminal screen with a lot more precision than \r or \b You may find the example at A du(1) real-time sorter using Curses easy to modify for your purposes.

    cheers

    tachyon

Re: Oddity with \r printing
by revdiablo (Prior) on Oct 19, 2004 at 21:31 UTC

    The reason is \r moves the cursor back to the front of the line, but does not erase any of the text that's there. I usually use substr with spaces for padding to avoid this issue. Example:

    my $width = 6; for (qw(1001 1002 200)) { print "\r" . substr($_ . " " x $width, 0, $width); }