How to merge two seperate arrays into hash in perl without loosing redundant values?

Viewed 98

I have two array's:

@arr  = qw(feature1 feature2 feature3);
@arr2 = qw(prod1 prod2 prod3 prod4);

I need a final hash in perl which would look like:

%hash = {
  feature1 => prod1,
  feature2 => prod2,
  feature3 => qw(prod3 prod4)
};

To merge the two arrays I used:

@hash{@feat} = @prod;
print Dumper \%hash;

How should I achieve this?

3 Answers

What you want is impossible as you can't have a list of values associated with the feature3 key. You'll need to have an array reference there instead.

You can't do it in a single assignment (or, at least, I can't think of a way to do it) but this seems to do it relatively simply.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my @feat = qw(feature1 feature2 feature3);
my @prod = qw(prod1 prod2 prod3 prod4);

my %hash;

if (@feat == @prod) {
  @hash{@feat} = @prod;
} else {
  @hash{@feat[0 .. $#feat - 1]} = @prod[0 .. $#feat - 1];
  $hash{$feat[$#feat]} = [ @prod[$#feat .. $#prod] ];
}

say Dumper \%hash;

Note, it assumes that either your two arrays are the same length, or @feat is shorter than @prod.

I'm not sure if this can be done with a single assignment but this is one way to do it. Note: the values are all array refs or undef if @arr2 is short. If you don't want the undef you'll need to extend the if statement.

use strict;

use Data::Dumper;

my @arr1=qw(feature1 feature2 feature3);
my @arr2=qw(prod1 prod2 prod3 prod4);

my %hash;
# if @arr2 is shorter than @arr1 then final hash values will be undef
if (@arr2 > @arr1) {
  @hash{splice(@arr1, 0, $#arr1)} = map { \[$_] } splice(@arr2, 0, $#arr1);
  $hash{$arr1[$#arr1]} = [ splice(@arr2, $#arr1) ]
} else {
  @hash{@arr1}=map { \[$_] } @arr2;
}

print Dumper(\%hash);

Got the answer to the problem

Solved it using references. In hash, Keys have to be unique and value can be redundant. I wanted to have "feature3 => qw(prod3 prod4)" and I achieved it using referencing where I created an empty array ref and pushed values each time the key appeared.

Please check the "Referencing in perl" for more details. This helped alot : https://mojolicious.org/perldoc/perlreftut

Thank you!

Related