我是 PERL 的新手,并且已经获得了我的第一个有用的脚本!现在我想增强它,但不明白如何使用数组来实现我的目标。我已经阅读了许多文章和帖子,但还不明白。
我正在使用的脚本计算给定扩展名的给定目录中的文件数并打印出来。我希望它还可以将文件名打印到初始指定目录中的 .txt 文件中。
任何建议或意见表示赞赏!我确定我需要使用数组来实现这个目标,我只是不明白如何将计数的文件名输入其中。我能够打印出数组列表,我只需要一些帮助来填充数组!非常感谢!
当前状态下的脚本:
#!usr/bin/perl
use strict;
use warnings;
use diagnostics;
use File::Find;
print "\n\n";
print "This script will start at the given directory and\nrecursively count the files of a given type\n\n\n";
print "-----------------------------------------------------------\n\n\n";
print "What directory would you like to start the count?\n\nDirectory Path: ";
my $dir = <STDIN>; #directory to begin search
chomp $dir;
print "\nWhat is the file extension you are searching for?\n\nFile Extension(.htm, .plx, .txt, etc.): ";
my $filext = <STDIN>; #file extension we're searching for
chomp $filext;
my $count = 0;
find(sub{$count++ if $File::Find::name =~ /$filext$/}, $dir);
if ($count > 0){
print "\n$count files counted, \n"; #display the number of files counted with the given file extension in the given directory
}
else {
print "Couldn't find any files to count.\n"; #if no files of the given type are found in the given directory
}
更新:
谢谢韦斯。我知道它现在是如何工作的,并感谢您抽出时间回复。
对于任何感兴趣的人,这是最终代码:
#!usr/bin/perl
use strict;
use warnings;
use diagnostics;
use File::Find;
print "\n\n";
print "This script will start at the given directory and\nrecursively count the files of a given type\n\n\n";
print "-----------------------------------------------------------\n\n\n";
print "What directory would you like to start the count?\n\nDirectory Path: ";
my $dir = <STDIN>; #directory to begin search
chomp $dir;
print "\nWhat is the file extension you are searching for?\n\nFile Extension(.htm, .plx, .txt, etc.): ";
my $filext = <STDIN>; #file extension we're searching for
chomp $filext;
my $count = 0;
my @files;
find(sub{
if ($File::Find::name =~ /$filext$/) {
push @files, $File::Find::name;
$count++;
}
}, $dir);
if ($count > 0){
print "\n\n-----------------------------------------------------------\n\n\n";
print "\n$count files counted: \n\n"; #display the number of files counted with the given file extension in the given directory
foreach (@files){
print "$_\n";
}
}
else {
print "Couldn't find any files to count.\n"; #if no files of the given type are found in the given directory
}