<STDIN> in List Context
One previously seen operator that returns a different value in an array context is the line-input operator, <STDIN>. As described earlier, <STDIN> returns the next line of input in a scalar context. Now, in list context, this operator returns all of the remaining lines up to the end of file. Each line is returned as a separate element of the list as in this example:
@lines = <STDIN>; # read standard input in list context
When the input is coming from a file, this will read the rest of the file. But how can there be an end-of-file when the input comes from the keyboard? On Unix and similar systems, including Linux and Mac OS X, you’ll normally type a Ctrl-D[86] to indicate to the system that there’s no more input. The special character is never seen by Perl, though it may be echoed to the screen. On DOS/Windows systems, use Ctrl-Z instead.[87] You’ll need to check the documentation for your system or ask your local expert if it’s different from these.
If the person running the program types three lines and presses the proper keys needed to indicate end-of-file, the array will have with three elements. Each element will be a string that ends in a newline, corresponding to the three newline-terminated lines entered.
Wouldn’t it be nice if, having read those lines, you could chomp the newlines all at once? It turns out that if you give chomp an array holding a list of lines, it will remove the newlines from each item in the list as in this example:
@lines = <STDIN>; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access