我需要
-
从指定目录中读取文件列表
-
创建描述这些文件的哈希数组
我的程序从命令行获取目录的路径,打开它并读取其内容 . 将跳过目录和“点”文件,并打印每个其他条目的绝对路径 .
use strict;
use warnings;
use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);
my $dir = $ARGV[0];
opendir DIR, $dir or die "cannot open dir $dir: $!";
while ( my $file = readdir DIR ) {
next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
next if ( "$file" =~ m/^\./) ;
print "${ \File::Spec->rel2abs($file) }\n";
}
closedir DIR;
在这里,我获取一个文件并使用路径,大小和sha256sum创建一个哈希 .
my $file = "file1.txt";
my @fileref = (
{
path => "Full path: " . File::Spec->rel2abs($file),
size => "Size (bytes): " . -s $file,
id => "SHA256SUM: " . sha256_hex($file),
},
);
print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";
所有这些都有效,但我无法弄清楚如何迭代每个文件并将其添加到数组中 .
这就是我的计划
for each file
push file into array
add the path, size, and id key:value pairs to file
repeat
如何生成必要的数组?
3 回答
感谢Wumpus Q.Wumbley的
push
建议,我已经解决了我的问题:我为哈希创建"frame",然后通过引用和
push
函数将其传递给数组 .这里's my approach to a solution. I'已经使用
File::Spec::Functions
而不是File::Spec
保存了很多代码,并且只调用rel2abs
一次我还从散列中的值中删除了标签,如
"Full path: "
. 有's no reason to put presentation strings in there: that' s用于输出代码您拥有所有代码,您正在使用第一个元素创建一个数组 . 您的解除引用方式暗示了一种简单的方法来添加其他内容: