in reply to Trouble iterating through a hash
i agree with 1nickt that Text::CSV_XS could be easier, but you say, "this isnt a csv file, it has TABS. well Text::CSV_XS isnt about csv files as much as delimted files, and will take a tab delimiter just as easily.
to show you how easy it is to use Text::CSV_XS i rewrote your code using it. I fixed a few things, ya get yelled at here if you dont use 3 arg opens or lexical limited filehandles ($file1,$file2). i fixed the funny next if 1..$N==$.; to just plain next if ($.==1); and like 1nickt i assumed you meant $prog in the second loop rather than $ID. Another thing i did was follow your code rather than your specs, "and print columns 3 and 5 of whole_pedigree" but your code uses columns 4 and 6 instead.
There are many parts of 1nickt's code that made sense, like skipping $hash2 and the whole {info1} subtree, but i felt if you saw Text::CSV_XS used in a way more like your original code you may appreciate it more. It came with Activestate perl, so i suspect it is in core and doesnt need to be installed either.#!/usr/bin/perl use warnings; use strict; use diagnostics; my $hash1; my $hash2; use Text::CSV_XS; my $sep="\t"; my $csv = Text::CSV_XS->new ({ sep_char => $sep }); open (my $file1, "<","wholepedigree_F.txt") or die "Couldn't open whol +epedigree_F.txt \n"; while (my $row = $csv->getline ($file1)) { next if ($.==1); my ($ID, $sire, $dam, $F, $FB, $AHC, $FA) = @$row; if ($ID){ $hash1 -> {$ID} -> {info1} = "$F\t$AHC"; } } close $file1; my $Output=\*STDOUT; open (my $file2, "<","damF.txt") or die "Couldn't open damF.txt\n"; while (my $row = $csv->getline ($file2)) { next if ($.==1); my ($damID, $damF, $damAHC, $prog) = @$row; if ($prog){ $hash2 -> {$prog} -> {info2} = "$damID\t$damF\t$damAHC"; } if ($prog && ($hash1->{$prog})) { my $info1 = $hash1 -> {$prog} -> {info1}; my $info2 = $hash2 -> {$prog} -> {info2}; print "$prog\t$info1\t$info2\n"; } } close $file2; print "Done";
I also didnt use the Text::CSV_XS output routines, so you could comare to your program easier.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trouble iterating through a hash
by huck (Prior) on Mar 09, 2017 at 05:34 UTC |