Search code examples
perlsplitwc

Count # lines in perl using wc


This seems really simple but neither a google search nor a stackoverflow search turn anything up. Is there a reason people don't do it this way? Sorry if I'm missing something.

I tried

$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";
}

but that doesn't split the output of wc -l for some reason.


Solution

  • Your code works on my computer, perhaps this is one of the reasons people avoid using external tools. You can do this with native Perl of course:

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