[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Perl hash or array

Posted on 2011-05-13
3
Medium Priority
?
476 Views
Last Modified: 2012-05-11
I want to create a hash of list in the following fashion:
Data:
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
0
Comment
Question by:farzanj
3 Comments
 
LVL 10

Assisted Solution

by:jeromee
jeromee earned 800 total points
ID: 35754356
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");
or
  push(@{$hash{gr4}}, qw(peter paul));
or
  my @lists = qw(julie jane);
  push(@$hash{gr4}, @lists);

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


Good luck!



0
 
LVL 27

Accepted Solution

by:
wilcoxon earned 1200 total points
ID: 35754672
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...
0
 
LVL 31

Author Closing Comment

by:farzanj
ID: 35770536
Thank you so much for your precious time.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question