我是 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
}
最佳答案
您传递给 find
的匿名子程序可以执行多个语句,就像普通子程序一样。
my @files;
find(sub{
if ($File::Find::name =~ /$filext$/) {
push @files, $File::Find::name;
$count++;
}
}, $dir);
您还可以像这样检查数组的大小:my $count = scalar @files;
而不是保留单独的计数
关于perl - 如何打印统计的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16089456/