开发者

How does my Perl program get standard input on Linux?

开发者 https://www.devze.com 2023-01-17 06:24 出处:网络
I am fairly new to Perl programming, but I have a fair amount of experience with Linux. Let’s say I have the following code:

I am fairly new to Perl programming, but I have a fair amount of experience with Linux. Let’s say I have the following code:

while(1) {
    my $text = <STDIN>;
    my $text1 = <STDIN>;
    my $text2 = <STDIN>;
}
开发者_StackOverflow

Now, the main question is: Does STDIN in Perl read directly from /dev/stdin on a Linux machine or do I have to pipe /dev/stdin to the Perl script?


If you don't feed anything to the script, it will sit there waiting for you to enter something. When you do, it will be put into $text and then the script will continue to wait for you to enter something. When you do, that will go into $text1. Subsequently, the script will once again wait for you to enter something. Once that is done, the input will go into $text2. Then, the whole thing will repeat indefinitely.

If you invoke the script as

$ script < input

where input is a file, the script will read lines from the file similar to above, then, when the stream runs out, will start assigning undef to each variable for an infinite period of time.

AFAIK, there is no programming language where reading from the predefined STDIN (or stdin) file handle requires you to invoke your program as:

$ script < /dev/stdin


It reads directly from the STDIN file descriptor. If you run that script it will just wait for input; if you pipe data to it, it will loop until all the data is consumed and then wait forever.

You may want to change that to:

while (my $test = <STDIN>) {
   # blah de blah
}

so an EOF will terminate your program.


Perl's STDIN is, by default, just hooked up to whatever the standard input file descriptor is. Beyond that, Perl doesn't really care how or where the data came from. It's the same to Perl if you're reading the output from a pipe, redirecting a file, or typing interactively at the terminal.

If you care about each of those situations and you want to handle each differently, then you might try different approaches.

0

精彩评论

暂无评论...
验证码 换一张
取 消