perl哈希中自动递增数字键值?

时间:2013-10-11 21:00:08

标签: arrays perl hash

我有一个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
         );

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

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

3 个答案:

答案 0 :(得分:6)

我不确定是否需要,但这应该

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

另一种方法

my $i = 0;
for( @builds ) {
  $hash{++$i} = $_;
}

答案 1 :(得分: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;

答案 2 :(得分:2)

另:

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

或:

my %hash = map { $_, $builds[$_-1] } 1..@builds;