Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^2: Comparing Hash key with array

by packetstormer (Monk)
on Feb 02, 2012 at 17:25 UTC ( #951500=note: print w/ replies, xml ) Need Help??

in reply to Re: Comparing Hash key with array
in thread Comparing Hash key with array

Yep, that is exactly what I would like to end up with.

Sorry for the confusion I am having trouble getting my head around the data structure itself but what you said above seems to be correct. - Thanks

Comment on Re^2: Comparing Hash key with array
Replies are listed 'Best First'.
Re^3: Comparing Hash key with array
by Riales (Hermit) on Feb 02, 2012 at 17:32 UTC

    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', '', '', ], ); 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!


    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; } }

      Excellent! Thanks, that works as I want.
      It turns out my original code, albeit verbose, almost works when I change that "==" to "eq". One of those things were you can't see the wood for the trees!

      Thanks for the tip regarding iterating through @lines. There will be an huge amount of data in there when it goes live.

      Thanks again

        Glad that worked for you! I just wanted to make sure you saw my edit--your code will run far faster if you iterate through @lines first.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://951500]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2015-11-28 17:53 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (743 votes), past polls