【问题标题】:Count # lines in perl using wc使用 wc 计算 perl 中的 # 行
【发布时间】:2013-06-06 00:51:24
【问题描述】:

这看起来很简单,但无论是 google 搜索还是 stackoverflow 搜索都没有找到任何结果。人们有理由不这样做吗?抱歉,如果我遗漏了什么。

我试过了

$B = `wc -l $fileB`;
print "$B\n";
@B_array = split /\s+/, $B; #try to split on whitespace
foreach my $item (@B_array) {
        print "$item\n";
}

但由于某种原因,这不会拆分wc -l 的输出。

非常感谢。

迈克尔

【问题讨论】:

  • 你的输出是什么样的?你可以使用split(' ', $B)

标签: perl split wc


【解决方案1】:

您的代码可以在我的计算机上运行,​​这也许是人们避免使用外部工具的原因之一。当然,您可以使用本机 Perl 做到这一点:

my $lc = 0;
open my $file, "<", "input" or die($!);
$lc++ while <$file>;
close $file;
print $lc, "\n";

【讨论】:

    【解决方案2】:

    这样可以避免拆分问题,但是这样使用 cat 会被认为是资源浪费。

    $B = `cat $fileB | wc -l`;
    

    cat filename | wc -l 只产生一些行——wc 在从管道读取到标准输入时无法获取文件名。

    @array=split ' ', $B 也适合你。

    【讨论】:

    • 使用cat如何避免分裂问题?
    • @squiguy,wc 输出中没有文件名是为什么 :)
    • @perreal 没错,只是打印一个数字吧?
    • 它产生 nnnnnn 作为输出而不是 nnnnnn 文件名
    猜你喜欢
    • 2010-11-27
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多