in reply to Need advice on checking two hashes values and keys
G'day perlynewby,
You're sort of on the right track. Here's where I see problems:
Having pointed out places where there's problems, I will commend you on the IO: lexical filehandles; 3-argument open; checking return values; using $!. All good - well done! In the examples below, I've used Inline::Files. Read about it if you want. The only pertinent part is that I'm using a while loop with a filehandle: read it the same as your code, I'm just using a different filehandle.
"check if the number is found in both files."
Let's start with doing just that and nothing else.
#!/usr/bin/env perl -l use strict; use warnings; use Inline::Files; my %seen; while (<ITES>) { ++$seen{(split)[0]}; } while (<ITFR>) { my $key = (split)[0]; print $key if $seen{$key}; } __ITES__ uno = uno due = dos tre = tres quattro = quatro cinque = cinco sei = seis sette = siete otto = ocho nouve = nueve dieci =diez __ITFR__ uno = un due = due tre = tris quattro = quatre cinque = cinq sei = six sette = sept dieci = dix
Output:
uno due tre quattro cinque sei sette dieci
Now you have working code that does what you want. One hash; two while loops; no foreach required.
Let's build on that to get the output you're after.
#!/usr/bin/env perl -l use strict; use warnings; use Inline::Files; my %seen; while (<ITES>) { chomp; my ($key, $val) = split /\s*=\s*/; $seen{$key} = $val; } while (<ITFR>) { chomp; my ($key, $val) = split /\s*=\s*/; print "$key => $seen{$key}, $val" if $seen{$key}; } __ITES__ uno = uno due = dos tre = tres quattro = quatro cinque = cinco sei = seis sette = siete otto = ocho nouve = nueve dieci =diez __ITFR__ uno = un due = due tre = tris quattro = quatre cinque = cinq sei = six sette = sept dieci = dix
Output:
uno => uno, un due => dos, due tre => tres, tris quattro => quatro, quatre cinque => cinco, cinq sei => seis, six sette => siete, sept dieci => diez, dix
As you can see, the basic structure of the code hasn't changed. The first while loop is almost identical to yours (with the regex fixed).
The second while loop starts like yours. But then just uses the same print ... if $seen{$key}; from my first example; the only real difference is that, having captured more data, we now have more information to print.
To learn more about hashes in Perl, see "perldata - Perl data types" and "perldsc - Perl Data Structures Cookbook".
Lastly, you have spelling mistakes in your data. For instance, two and three in French are deux and trois. I'll leave you to check the rest.
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Need advice on checking two hashes values and keys
by perlynewby (Scribe) on Jun 04, 2015 at 21:02 UTC | |
by kcott (Archbishop) on Jun 04, 2015 at 21:55 UTC |