• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 482
  • Last Modified:

Perl hash or array

I want to create a hash of list in the following fashion:
keys     values
gr4       john
gr5       alice
gr4       mike
gr2       andrew
gr5       adam
gr4       don

It should create a hash of lists in a sequential fashion on the fly (dynamically) as follows

%hash = (gr4 => [john,mike,don], gr2 =>[andrew], gr5 =>[alice,adam])

I want as least conditions as possible.  Hopefully should get a way to add to empty lists and existing lists in the same condition
2 Solutions
This should work
%hash = (gr4 => [qw(john mike don)], gr2 =>['andrew'], gr5 =>[qw(alice adam)]);
and if you want to add more you can do something like thisL
  push(@{$hash{gr4}}, "farzan");
  push(@{$hash{gr4}}, qw(peter paul));
  my @lists = qw(julie jane);
  push(@$hash{gr4}, @lists);

For an empty list:
  $hash{gr0} = [];

Good luck!

This should do it...

The most direct would be using this pair of lines where you want to add values:

$hash{$key} = [] unless $hash{$key};
push @{$hash{$key}}, $val;

If you need to do that a lot, it might be worth creating a sub like this:

# used wherever needed
add_val($key, $val);

# defined once
sub add_val {
    my ($key, $val) = @_;
    $hash{$key} = [] unless $hash{$key};
    push @{$hash{$key}}, $val;

Please let me know if you need more assistance...
farzanjAuthor Commented:
Thank you so much for your precious time.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now