3

我有一个 perl 脚本,我在其中从给定目录读取文件,然后将这些文件放入数组中。然后我希望能够将这些数组元素移动到 perl 哈希中,数组元素是哈希值,并自动将数字键分配给每个哈希值。

这是代码:

    # Open the current users directory and get all the builds. If you can open the dir
    # then die.
    opendir(D, "$userBuildLocation") || die "Can't opedir $userBuildLocation: $!\n";
    # Put build files into an array.
    my @builds = readdir(D);
    closedir(D);
    print join("\n", @builds, "\n");

这个打印出来:

    test.dlp
    test1.dlp

我想获取这些值并将它们插入到一个看起来像这样的哈希中:

my %hash (
            1 => test.dlp
            2 => test1.dlp
         );

我希望编号键根据我在给定目录中找到的文件数量自动递增。

我只是不确定如何将自动递增键设置为哈希中每个项目的唯一数值。

4

3 回答 3

7

我不确定是否了解需求,但这应该可以

my $i = 0;
my %hash = map { ++$i => $_ } @builds;

另一种方法

my $i = 0;
for( @builds ) {
  $hash{++$i} = $_;
}
于 2013-10-11T21:05:47.993 回答
6

最直接最无聊的方式:

my %hash;
for (my $i=0; $i<@builds; ++$i) {
  $hash{$i+1} = $builds[$i];
}

或者,如果您愿意:

foreach my $i (0 .. $#builds) {
  $hash{$i+1} = $builds[$i];
}

我喜欢这种方法:

@hash{1..@builds} = @builds;
于 2013-10-11T21:20:16.137 回答
2

其他:

my %hash = map { $_+1, $builds[$_] } 0..$#builds;

或者:

my %hash = map { $_, $builds[$_-1] } 1..@builds;
于 2013-10-11T23:44:35.257 回答