【问题标题】:I have 10 csv files in array and I want row count of each csv file using perl我在数组中有 10 个 csv 文件,我想使用 perl 对每个 csv 文件的行数
【发布时间】:2021-07-15 07:40:36
【问题描述】:

我在@files 中有 10 个 CSV 文件。现在我想计算每个 CSV 文件中的行数。我已经尝试了下面的代码,但它只返回了 CSV 数。

my $directory = 'C:\folder';
open "dir", $directory or die;
@files = readdir "dir";
close("dir");

请帮我实现上述场景。

【问题讨论】:

  • 如果你在 Unix/Linux 中,那么你可以使用wc -l file1 file2 file3 ... filen
  • 在某些情况下,您不能只计算行数,因为引用的字段可能有换行符。

标签: csv perl


【解决方案1】:

这可以帮助你:

#!/usr/bin/perl

use strict; use warnings;

my $directory = "/path/to/the/directory/";
my @files = glob("$directory*.csv");

foreach my $file (@files){
    my $lines = 0;
    open (FILE, $file) or die "Can't open '$file': $!";
    $lines++ while (<FILE>);
    close FILE;

    print "File:$file = $lines\n";
}

在 Ubuntu 20.04 (Perl v5.30.0) 中测试过。

【讨论】:

  • 为什么不使用my @lines = &lt;FILE&gt;; say scalar @lines?还是您希望文件很大?
  • @PolarBear:是的,这也是可能的。
【解决方案2】:

这是一个常见问题解答。

How do I count the number of lines in a file?

答案在决定之前讨论了解决问题的多种方法:

如果您不介意脱壳,wc 命令通常是最快的,即使有额外的进程间开销。确保您有一个未污染的文件名:

#!perl -T

$ENV{PATH} = undef;

my $lines;
if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
    $lines = `/usr/bin/wc -l $1`
    chomp $lines;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2019-02-14
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多