gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:19:22 24 4
gpt4 key购买 nike

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

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

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

最佳答案

我不确定是否理解需要,但这应该可以

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

另一种方法来做到这一点
my $i = 0;
for( @builds ) {
$hash{++$i} = $_;
}

关于arrays - perl 哈希中的自动递增数字键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com