首页 > 解决方案 > Perl readdir 警告 - 名称“main::DIR”仅使用一次:可能的错字

问题描述

我有一个脚本,它列出了特定目录中的可能文件。该代码工作正常,但如何避免此警告?

#!/usr/bin/perl

use strict;
use warnings;
use autodie;

my $logpath = "C:/Users/Vinod/Perl/Log";

opendir(DIR, $logpath);
while (my $file = readdir(DIR)) {

    next unless (-f "$logpath/$file");
    print "FILENAME:$file\n";

}
closedir(DIR);

编译或运行脚本时显示的警告是:

$ perl -cw log_fetch.pl
Name "main::DIR" used only once: possible typo at log_fetch.pl line ...
log_fetch.pl syntax OK

标签: perl

解决方案


这似乎是使用use autodie;.

可以按如下方式使警告静音:

sub x { *DIR }  # Silence spurious "used only once" warning.

但是,您不必要地使用全局变量 ( *DIR)。使用词法变量会好得多,这将解决问题。

opendir(my $DIR, $logpath);

推荐阅读