Nick Bitzer
Nick Bitzer

Reputation: 69

Auto increment numeric key values in a perl hash?

I have a perl script in which I am reading files from a given directory, and then placing those files into an array. I then want to be able to move those array elements into a perl hash, with the array elements being the hash value, and automatically assigning numeric keys to each hash value.

Here's the code:

    # 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");

This print out:

    test.dlp
    test1.dlp

I want to take those value and insert them into a hash that looks just like this:

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

I want the numbered keys to be auto incrementing based on how many files I may find in a given directory.

I'm just not sure how to get the auto-incrementing keys to be set to unique numeric values for each item in the hash.

Upvotes: 3

Views: 2888

Answers (3)

Mark Reed
Mark Reed

Reputation: 95315

The most straightforward and boring way:

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

or if you prefer:

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

I like this approach:

@hash{1..@builds} = @builds;

Upvotes: 6

ysth
ysth

Reputation: 98398

Another:

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

or:

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

Upvotes: 2

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

I am not sure to understand the need, but this should do

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

another way to do it

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

Upvotes: 7

Related Questions