Suppose there is a list that is input from the console using <STDIN>
@string = <STDIN>;
Now, I check for a pattern, say /manu/, in my program
foreach (@string)
{
if(/manu/)
{
print $_."\n";
}
}
The code is unable to look for the pattern /manu/.
However when I do the following, the code works perfectly fine:
chomp(@string = <STDIN>);
Why?
Edit: My original answer was written assuming the code posted was the code the OP had used. Updated after the correction.
Here is what I get when run:
Output:
Note the Control-Z which I use to signal EOF from the command line on Windows (if you are using a *nix shell, you would use Control-D).
Output only appears once your program reads all the data it can read from
STDIN.Note the newline printed after
manu. That’s because I did notchompthe input. That is the only difference between using this code versus usingWhen you first assign
<STDIN>to an array and iterate over that, your program will wait until there is no more data to be read and its memory use will be proportional to the amount of data received.On the other hand, the following program will process lines as they come:
and its memory use will be proportional to the longest line received.
The line above is equivalent to:
Note that, you should always add
use strict;and its close frienduse warnings;to your scripts. See perldoc strict.