为什么(<>)perl无法计数或打印第一行

问题描述 投票:0回答:1

我想计算文件中的行数并打印一个取决于行号的字符串。但是我的while循环错过了第一行。我相信while (<>)构造对于增加$n变量是必需的;无论如何,这种构造在perl中不是很标准吗?

如何获得while循环以打印第一行?还是不应该使用while

> printf '%s\n%s\n' dog cat
dog
cat
> printf '%s\n%s\n' dog cat | perl -n -e 'use strict; use warnings; print; '
dog
cat
> printf '%s\n%s\n' dog cat | perl -n -e 'use strict; use warnings; while (<>) { print; } ' 
cat
> 
> printf '%s\n%s\n' dog cat | perl -n -e 'use strict; use warnings; my $n=0; while (<>) { $n++; print "$n:"; print; } ' 
1:cat
perl while-loop stdin
1个回答
0
投票

man perlrun显示:

   -n   causes Perl to assume the following loop around your program, which makes it iterate over filename
        arguments somewhat like sed -n or awk:

          LINE:
            while (<>) {
                ...             # your program goes here
            }

        Note that the lines are not printed by default.  See "-p" to have lines printed.  If a file named by an
        argument cannot be opened for some reason, Perl warns you about it and moves on to the next file.

        Also note that "<>" passes command line arguments to "open" in perlfunc, which doesn't necessarily
        interpret them as file names.  See  perlop for possible security implications.
 ...
 ...     

      "BEGIN" and "END" blocks may be used to capture control before or after the implicit program loop, just as in awk.

因此,实际上您正在运行此脚本

LINE:
    while (<>) {
        # your progrem start
        use strict;
        use warnings;
        my $n=0;
        while (<>) {
            $n++;
            print "$n:";
            print;
        }
        # end
    }

解决方案,只需移除-n

printf '%s\n%s\n' dog cat | perl -e 'use strict; use warnings; my $n=0; while (<>) { $n++; print "$n:"; print; }'

将打印:

1:dog
2:cat

printf '%s\n%s\n' dog cat | perl -ne 'print ++$n, ":$_"'

结果相同

printf '%s\n%s\n' dog cat | perl -pe '++$n;s/^/$n:/'
© www.soinside.com 2019 - 2024. All rights reserved.