我开始自学 Perl,在一些谷歌搜索的帮助下,我能够编写一个脚本,打印出给定目录中的文件扩展名。该代码运行良好,但是有时会抱怨以下内容:
Use of uninitialized value $exts[xx] in string eq at get_file_exts.plx
我试图通过如下初始化我的数组来纠正这个问题:my @exts = (); 但这并没有按预期工作。
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
#Check for correct number of arguments
if(@ARGV != 1) {
print "ERROR: Incorrect syntax...\n";
print "Usage: perl get_file_exts.plx <Directory>\n";
exit 0;
}
#Search through directory
find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);
my @exts;
sub process_file {
if (-f $_) {
#print "File: $_\n";
#Get extension
my ($ext) = $_ =~ /(\.[^.]+)$/;
#Add first extension
if(scalar @exts == 0) {
push(@exts, $ext);
}
#Loop through array
foreach my $index (0..$#exts) {
#Check for match
if($exts[$index] eq $ext) {
last;
}
if($index == $#exts) {
push(@exts, $ext);
}
}
} else {
#print "Searching $_\n";
}
}
#Sort array
@exts = sort(@exts);
#Print contents
print ("@exts", "\n");