1

I was taking inspiration from this post https://stackoverflow.com/a/16157433/3880362. The only thing that it did not do was increment the value of each key as it was populated. I.e.

I have:

$Hash => {
      'Val1' => 1,
      'Val2' => 1,
      'Val3' => 1
 };

When I want

$Hash => {
      'Val1' => 0,
      'Val2' => 1,
      'Val3' => 2
 };

Code:

$Hash{$_}++ for (@line);
2
  • 1
    $Hash{$_}=keys %Hash for (@line); Commented Mar 2, 2018 at 23:10
  • What about using the index of the array as the value? Something like this: perl -MData::Dump -e '@line = qw(apple banana cherry tree); $hash{$line[$_]} = $_ for 0..$#line; END {dd \%hash}' { apple => 0, banana => 1, cherry => 2, tree => 3 }. Otherwise can maybe set up a counter variable, but not sure if you can do it without a loop. Commented Mar 2, 2018 at 23:11

3 Answers 3

3

Based on the other question, your input is @array and your output is %hash where the values of the hash are offset in the array of the hash's keys in the array. If so, I think you want this:

$hash{$array[$_]} = $_ for (0 .. $#array);
Sign up to request clarification or add additional context in comments.

2 Comments

Putting some keywords here, because this is a good answer. This is like a value-to-index hash. Good for doing something like a CSV header.
ie: $value2idx{$values[$_]} = $_ for 0..$#values; where what being iterated is the array index. The first comment on the OP also does the same thing iterating the values.
1

You can iterate over the array indices and use those to populate the hash values. Perl arrays start at index 0. The last index of array @foo is $#foo. So you can use the range operator .. to get all of the indices as 0..$#foo.

#!/usr/bin/env perl

use warnings;
use strict;

use Data::Dumper;
$Data::Dumper::Sortkeys++;

my @letters = 'a'..'g';
my %hash = map { $letters[ $_ ] => $_ } 0..$#letters;

print Dumper(\%hash);

output

$VAR1 = {
          'a' => 0,
          'b' => 1,
          'c' => 2,
          'd' => 3,
          'e' => 4,
          'f' => 5,
          'g' => 6
        };

Comments

0

I think that you want to turn all elements of array @line into hash keys of hash %hash with hash values going from 0 on. In that case:

use Data::Dumper;

my @line = qw( Val1 Val2 Val3 );
my %hash;

my $n = 0;
$hash{$_} = $n++ for(@line);

print Dumper(\%hash), "\n";

Note that Dumper will dump all the hash keys and their values, but not in the order they were created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.