开发者

Why is this pattern not matching the data my program reads from STDIN?

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 prog开发者_高级运维ram

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:

#!/usr/bin/perl

use strict; use warnings;

my @string = <STDIN>;

for (@string) {
    if(/manu/) {
        print "'$_'";
    }
}

Output:

E:\> t
manu
nana
tada
^Z
'manu
'

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 not chomp the input. That is the only difference between using this code versus using

chomp(my @string = <STDIN>)

When 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:

/manu/ and print while <>;

and its memory use will be proportional to the longest line received.

The line above is equivalent to:

while ( <> ) {
    if ( /manu/ ) {
        print $_;
    }
}

Note that, you should always add use strict; and its close friend use warnings; to your scripts. See perldoc strict.


In your first example, @list is undefined. If you would have had

use strict;
use warnings;

in your script (highly recommended!), Perl would have told you about this.

Edit: Now that you've fixed this, the code you have works for me.


chomp tears off any whitespace or cr/lfs. Add a chomp, or add any whitespace to your regex match, eg:

foreach (@string)
{
    if(/manu\s*/)
    {
        print $_."\n";
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜