Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Printing from stdin to stdout

by Athanasius (Archbishop)
on Aug 26, 2019 at 02:48 UTC ( [id://11105017]=note: print w/replies, xml ) Need Help??


in reply to Printing from stdin to stdout

Hello harangzsolt33,

Angle brackets around a filehandle are a special Perl construct for calling the built-in readline function, which (like most Perl functions) behaves differently according to the context in which it appears. From the documentation:

In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns undef. In list context, reads until end-of-file is reached and returns a list of lines.

The line my $L = <STDIN>; supplies a scalar context, and so only one line is read since readline is called only once.

By contrast, the line print <STDIN>; supplies a list context (see print), so multiple lines may be read in by a single call.

Change your second example as follows: my @L = <STDIN>; print @L; and you will see the same behaviour as in the first example. On Windows (where ^Z signals end-of-file):

12:31 >perl -wE "my @L = <STDIN>; print @L;" abc def ghi ^Z abc def ghi 12:31 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Printing from stdin to stdout
by harangzsolt33 (Chaplain) on Aug 26, 2019 at 03:30 UTC
    Wow! That explains it. I didnt know that print creates a list context.

    Thank you very much for your quick answer on a Sunday evening!!

      Note that a simple way to force scalar context on anything is scalar, as in print scalar <STDIN>;.

        Also note that while there is no similar keyword for forcing list context, it can be done with @{[]}, as in print @{[<STDIN>]}, but actually using that is an advanced feature and if you force list context in a scalar context, you will get the number of items in the list rather than any of the values in list.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11105017]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-29 15:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found