in reply to Re^2: Comparing Hash key with array
in thread Comparing Hash key with array
This should work:
use Data::Dumper; my @lines = ( ['_W9C2JJDCB', 'asdf1', 'zxcv1', ], ['_W9C2JJDCB', 'asdf2', 'zxcv2', ], ['_W9C2JJDCB', 'asdf3', 'zxcv3', ], ); my %hash = ( '_W9C2JJDCB' => [ '_W92CJJDCB', '201200240', 'TEST: IGNORE', 'John Doe', 'Closed', 'HIP', 'email@email.com', 'email2@email.com', ], ); foreach my $key (keys %hash) { foreach my $line (@lines) { if ($line->[0] eq $key) { shift @$line; push @{$hash{$key}}, @$line; } } } die Dumper(%hash);
I don't know what your input data looks like, but may I suggest iterating through @lines instead of keys %hash in the outer loop? This way, you can use the hash's look-up to check if there's a match. Your way is better if there's a massive amount of data in @lines that doesn't have a match in %hash though. Let me know if you'd like some help with the other way!
EDIT: I TAKE BACK WHAT I SAID
You should definitely iterate through @lines first no matter what; it's far more efficient:
foreach my $line (@lines) { my $key = shift @$line; if (exists($hash{$key})) { push @{$hash{$key}}, @$line; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Comparing Hash key with array
by packetstormer (Monk) on Feb 02, 2012 at 17:43 UTC | |
by Riales (Hermit) on Feb 02, 2012 at 17:50 UTC |