Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: updated: how to loop through hash tables more efficiently

by Anonymous Monk
on Sep 18, 2012 at 01:59 UTC ( #994167=note: print w/replies, xml ) Need Help??

in reply to updated_again: how to loop through hash tables more efficiently

If you simplify your data structure you can ditch internal loops, not that it matters

#!/usr/bin/perl -- use strict; use warnings; my ( $hash1, $hash2 ) = @ARGV or die "$!"; my $h1 = read_hash( $hash1, 'reverse' ); my $h2 = read_hash($hash2); use Data::Dump; dd $h1, $h2; while ( my ( $key, $val ) = each %$h2 ) { if ( exists $h1->{$val} ) { print "$key,$h1->{$val}\n"; } } sub read_hash { my $fname = shift; my $reverse = shift || 0; open( my $fh, "<", $fname ) or die "open( < $fname ): $!"; my %hash = (); while ( my $line = <$fh> ) { chomp $line; my ( $key, @vals ) = split /,/, $line; if ( not $reverse ) { ( $hash{$key} ) = @vals; } else { @hash{@vals} = ($key) x int(@vals); } } return \%hash; } __END__ $ perl hash1 hash2 ( { val_a1 => "k_a1", val_a2 => "k_a1", val_a3 => "k_a1", val_a4 => "k_a2", val_a5 => "k_a2", }, { k_b1 => "val_a1", k_b2 => "val_a2", k_b3 => "val_a3", k_b4 => "val_a4", k_b5 => "val_a5", }, ) k_b1,k_a1 k_b4,k_a2 k_b5,k_a2 k_b3,k_a1 k_b2,k_a1

Replies are listed 'Best First'.
Re^2: updated: how to loop through hash tables more efficiently
by Kenosis (Priest) on Sep 18, 2012 at 04:55 UTC

    This is a brilliant solution...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://994167]
[stevieb]: I am thankful that I fell into Perl years ago in the manner I did. I don't believe there is another language that people care about so much, that they're willing to give everything. Langs come and go, but in Perl, it seems, things remain consistent.
[stevieb]: The people back then (~2000) are the same people now, but with much more experience. I'm appreciative that I fell into the Perl rabbit hole.
[stevieb]: Coding circles around Python devs, showing how unit tests should be done, enabling easy access to everything, learning basic C to wrap for direct hardware access... I am thankful.
[stevieb]: I'm in an appreciative mood. Thank you fellow Monks, for all I know, and for the knowledge which I can pass on

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2017-02-25 01:22 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (364 votes). Check out past polls.