为什么我不能将一个参数传递给sub

时间:2014-03-06 09:17:03

标签: perl

输入是目录名称,输出是目录中的文本文件名,文件名,行数,字数。 当我检查这个程序时,我可以知道第二个子工作的时候,$ _就像是“”。

我该如何解决?

#!/usr/bin/perl
use strict; use warnings;
my $dir = <STDIN>;
chomp($dir); # remove '\n'(new-line character) from directory address
opendir(dirHandle, "$dir"); 
my @arr = readdir(dirHandle);
close(dirHandle);
foreach(@arr){
    if($_ =~ /.txt/){
        print "File Name : $_\n";       
        my $tmp = $_;
        print "Line Numb : ".&how_many_lines($_)."\n";
        print "Word Numb : ".&how_many_words($_)."\n\n";
    }
}
sub how_many_lines{
    open(FILE, "$_") || die "Can't open '$_': $!";
    my $cnt=0;
    while(<FILE>){ 
        $cnt++;
    }
    close(FILE);
    return $cnt;
}
sub how_many_words{
    open(TEXT, "$_") || die "Can't open '$_': $!";
    # error! printed "Can't open ''" : No such file or directory
    my $cnt=0;
    while(<TEXT>){
        my @tmp = split(/ /, $_);
        my $num = @tmp;
        $cnt += $num;
    }
    close(TEXT);
    return $cnt;
}

1 个答案:

答案 0 :(得分:1)

您不能使用$_来引用子的第一个参数。它应该是$_[0],数组@_的第一个元素,它是参数列表。

在sub中检索参数的最惯用(不要与愚蠢的混淆)方法是这样的:

my $filename = shift;  # shift uses @_ automatically without arguments

Perl允许标量,数组和散列使用相同的名称:$foo@foo%foo是不同的实体。将数组@foo索引为零时,它变为$foo[0]。这与$foo不同。

相关问题