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

fellow monks,

#!/usr/bin/perl use strict; print ":Hello ^M world:\n";
Output :-
World:
In the above code, I typed "Hello World" as follows :-
Hello <ctrl+v><ctrl+m>world
Could any one explain me the output which I got ?

Replies are listed 'Best First'.
Re: adding non printable characters in perl's print function
by ikegami (Patriarch) on Feb 21, 2007 at 06:36 UTC

    Character 13, in ASCII and derived character sets, is Carriage Return (CR). It is a non-printable character that terminals usually interpret as a request to move the cursor to the start of the current line.

    It can be represented as \r (at least on Windows and unix systems), \x0D and \015 in Perl string literals to avoid the trouble of actually placing the character in the literal.

    Some fun with \r:

    $| = 1; # Turn off buffering on STDOUT. print( " 5"); sleep(1); print("\r 4"); sleep(1); print("\r 3"); sleep(1); print("\r 2"); sleep(1); print("\r 1"); sleep(1); print("\r** BOOM **\n");
      printf( "\r%5s", $_), sleep( /\d/) for reverse "\r** BOOM **\n", 1 .. 5; # :)

      Anno

        The purpose of the snippet was to highlight the effect of \r, not to hide it.
Re: adding non printable characters in perl's print function
by Zaxo (Archbishop) on Feb 21, 2007 at 06:29 UTC

    Control-M is carriage return without linefeed. ":Hello " is printed, then the print position returns to the start of the line and "World:" overwrites it.

    That is often used for text-mode progress counters and spinners.

    After Compline,
    Zaxo

Re: adding non printable characters in perl's print function
by redlemon (Hermit) on Feb 21, 2007 at 10:20 UTC

    A quick way to check your output to see everything you put in comes out is to use the 'od' command (on any unix-like box):

    perl -e 'print ":Hello ^M world:\n"' | od -c

    This will give you

    0000000   :   H   e   l   l   o      \r       w   o   r   l   d   :  \n

    --
    Lyon

Re: adding non printable characters in perl's print function
by dsheroh (Monsignor) on Feb 21, 2007 at 16:07 UTC
    To answer the implicit half of your question, to get the effect of \n you need both a carriage return (to go to the start of the line) and a line feed (to go to the next line). This combination is frequently referred to as a "CRLF".
    #!/usr/bin/perl use strict; print ":Hello \x0D\x0A world:\n";
    This outputs
    :Hello world:
    Note that this is all a bit system-dependent, as \n represents only a LF on Unix-type systems (which add an implicit CR), only a CR on (pre-OS X) Macs (which add an implicit LF), and CRLF on Windows. So it's probably best to just use \n instead of mucking about with the literal control characters anyhow.