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

Notice the null character in the first example doesn't show up in the others.
[predb24:~/tests] $ cat lines.pl #!/usr/bin/perl open (TEST, ">test.txt"); print TEST "This is a test\n"; #print TEST "This is a test\n"; #print TEST "";<br/> close TEST;<br/> [predb24:~/tests] $ lines.pl [predb24:~/tests] $ od -cx test.txt 0000000 T h i s i s a t e s t \n \ +0 6854 7369 6920 2073 2061 6574 7473 000a 0000017 [predb24:~/tests] $ cat lines.pl #!/usr/bin/perl open (TEST, ">test.txt"); print TEST "This is a test\n"; print TEST "This is a test\n"; #print TEST ""; close TEST; [predb24:~/tests] $ lines.pl [predb24:~/tests] $ od -cx test.txt 0000000 T h i s i s a t e s t \n +T 6854 7369 6920 2073 2061 6574 7473 540a 0000020 h i s i s a t e s t \n 6968 2073 7369 6120 7420 7365 0a74 0000036 #!/usr/bin/perl open (TEST, ">test.txt"); print TEST "This is a test\n"; print TEST "This is a test\n"; print TEST ""; close TEST; [predb24:~/tests] $ lines.pl [predb24:~/tests] $ od -cx test.txt 0000000 T h i s i s a t e s t \n +T 6854 7369 6920 2073 2061 6574 7473 540a 0000020 h i s i s a t e s t \n 6968 2073 7369 6120 7420 7365 0a74 0000036 [predb24:~/tests] $ cat lines.pl #!/usr/bin/perl open (TEST, ">test.txt"); #print TEST "This is a test\n"; #print TEST "This is a test\n"; print TEST "\n"; close TEST; [predb24:~/tests] $ lines.pl [predb24:~/tests] $ od -cx test.txt 0000000 \n \0 000a 0000001
  • Comment on Why do I sometimes get null characters after the line feed when writing to files?
  • Download Code

Replies are listed 'Best First'.
Re: Why do I sometimes get null characters after the line feed when writing to files?
by dave_the_m (Monsignor) on Dec 18, 2006 at 16:20 UTC
    The output doesn't contain a null character; its just an artifact of the way od displays contents in units of 2 bytes:
    $ echo "ab" > /tmp/foo $ ls -l /tmp/foo -rw-r--r-- 1 davem davem 3 Dec 18 16:16 /tmp/foo $ od -xc /tmp/foo 0000000 6261 000a a b \n \0 0000003 $ echo "abc" > /tmp/foo $ ls -l /tmp/foo -rw-r--r-- 1 davem davem 4 Dec 18 16:17 /tmp/foo $ od -xc /tmp/foo 0000000 6261 0a63 a b c \n 0000004 $
    (Note that the first one is length three, but od displays a fourth null byte.)

    Dave.

Re: Why do I sometimes get null characters after the line feed when writing to files?
by derby (Abbot) on Dec 18, 2006 at 16:17 UTC

    I believe that's really an artifact of od when the input is an odd number of bytes.

    -derby
Re: Why do I sometimes get null characters after the line feed when writing to files?
by graff (Chancellor) on Dec 18, 2006 at 23:44 UTC
    When I use a different set of options with "od", there is no problem:
    $ echo ab | od -cx # your method: 2-byte units in hex 0000000 a b \n + 6162 0a00 + 0000003 $ echo ab | od -c -t xC # my method: char-sized units in hex 0000000 a b \n + 61 62 0a + 0000003