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

Hello, I am trying to read data piped to the program via stdin.
It seems that an \x0a in the data will end what is taken as "<STDIN>".
Other "control" characters will go into STDIN ok and the buffer behaves as expected.
----- small example code -----
#!/usr/bin/perl -wT use strict; use warnings; my $s1 = <STDIN>; print("\$s1= <$s1> \n"); if (<STDIN>) { my $s2 = <STDIN>; print("\$s2= <$s1> \n"); };
----- some output samples: ----- (linux-gnome terminal)
perl> echo -ne "hello\x0aWorld" | ./pipe_x-1.pl # try \n $s1= <hello > $s2= <hello: > perl> echo -ne "hello\x0dWorld" | ./pipe_x-1.pl # try \r World> ello perl> echo -ne "hello\x09World" | ./pipe_x-1.pl # try \t $s1= <hello World>
As you can see the samples using 0x0d and 0x09 are read through to EOF and buffer is empty so the $s2 print does not occur.

But something wierd happens with the 0x0a.
Very interesting , what can I do to read through that?

Replies are listed 'Best First'.
Re: read through \x0a in data piped via STDIN
by mr_mischief (Monsignor) on Dec 09, 2010 at 17:54 UTC

    You're not reading to EOF.

    This:

    my $s1 = <STDIN>;

    reads exactly one line. Since $/ is "\n" (see perlvar), your line ends at "\n".

    If you want to read by line and get more than one line, I suggest some sort of iteration. Perhaps a while loop.

    The most common idiom for reading a whole file line by line in Perl is:

    while ( <$filehandle> ) { # do something }

    In your case, that'd be:

    while ( <STDIN> ) { # do something }

    There's really nothing mysterious going on. All of this is well-documented and widely known.

Re: read through \x0a in data piped via STDIN
by VinsWorldcom (Prior) on Dec 09, 2010 at 17:56 UTC

    Try adding:

    $/ = undef;

    after your 'use' statements:

    #!/usr/bin/perl use strict; use warnings; $/ = undef; my $s1 = <STDIN>; print("\$s1= <$s1> \n"); if (<STDIN>) { my $s2 = <STDIN>; print("\$s2= <$s1> \n") }

    By not defining (undef) the input record separator (default newline), it will read to EOF.

      Oh I see. It all make sense now. perlvar - tonight!
      Thank you all.
Re: read through \x0a in data piped via STDIN
by Anonyrnous Monk (Hermit) on Dec 09, 2010 at 17:54 UTC
    But something wierd happens with the 0x0a

    Well, <...>, aka readline, by definition reads up to the next input record separator, which by default is a newline, i.e. \n or 0x0a.

    You could change $/ ...