in reply to Strangely adding a "\n" character prints a variable

You are Suffering from Buffering

The '\n' newline character causes the file buffer to be flushed. Yes, STDOUT (in this case the screen) is considered a file. Without the newline, the buffer isn't flushed as often as you would probably like, and the result is that nothing gets printed (yet).

This is a pretty common problem. So common, in fact, that there's a new feature that you can use, called "say()". say() is identical to print(), but automatically appends the newline character for you. You have to tell perl to use the feature for it to be available. See say and feature for an explanation of how to enable and use say()

Have a look at the article I linked to at the top of this post.

If you don't mind, in the future, try to ask the question in a block of text preceding the code snippet. It's tedious trying to find the question embedded within the script.


Dave

Replies are listed 'Best First'.
Re^2: Strangely adding a "\n" character prints a variable
by iphone (Beadle) on Feb 03, 2011 at 09:10 UTC

    Thanks,that helped but this seems to be a problem only with newer versions of perl

      The article, Suffering from Buffering was published in The Perl Journal in 1998. If it wasn't a problem in older versions of Perl, why was it so well documented thirteen years ago?

      From the article:

      When a filehandle is attached to the terminal, as STDOUT is here, it is in line buffered mode by default. A filehandle in line buffered mode has two special properties: It's flushed automatically whenever you print a newline character to it, and it's flushed automatically whenever you read from the terminal.

      The implication here is that the line is NOT flushed automatically whenever you DON'T print a newline or read from the terminal.


      Dave

      In zsh (3 or 4) was where I found that output of a program -- which was being printed just fine in bash -- was not shown in the terminal anymore. Turns out that making shell to print a newline (most likely via shell prompt if not by some option), program output was being displayed on the terminal again. (Program might also have been updated to print a newline at the end.)