in reply to Compare hash with arrays and print

I reversed the hash to get a unique list of the "numbers". Then opened that many files and put the file handles in another hash. This eliminates some of the "if" logic. Using different record separator does help, but a slight bit of fiddling is required.

update: See how different filehandles are used in the print below. Also if what reverse is unclear add a print Dumper(\%rhash); statement.

#!/usr/bin/perl -w use strict; use Data::Dumper; my %hash = (aw1 => 10, qs2 => 20, dd3 => 30, de4 => 10, hg5 => 30, dfd6 => 20, gf4 => 20, hgh5 => 30, hgy3 => 10); my %rhash = reverse %hash; my %fh; foreach my $num (keys %rhash) { open ($fh{"$num.txt"} , '>', "$num.txt") or die ; } $/ = '>'; while (<DATA>) { my $tag = (m/^(\w+)/)[0]; #"blank" rec at beginning next unless defined $tag; s/>$//; my $filename = "$hash{$tag}.txt"; my $handle = $fh{$filename}; print $handle ">$_"; } __DATA__ >aw1 ATGCTAGATGCTAGCTAGCTAGCACTGAT CGATGCTAGCGTAGTCAGCTGATGCTGTA CGATGCTAGTCGTACG >qs2 CGAGCTAGTCGTAGTCGTGATGCTGATTA CGATGCTAGTCGTAGCTAGCTGATGCTGC CGATGCTAGTCGTAGTC >dd3 CGTAGTCGTAGTCGTAGTCGATGCTGATG GCTAGTCGATGCTAGCTAGTCGATGCTGG CGATGCTGAT >de4 CGTAGTCGTAGTCGTACGTAGTCGTGAGT CGATTATTTAGGAGGGACAAGGATAGTA >hg5 CGTAGTCGTAGTCTAGTCGTGATGCTAGA >dfd6 CGATGCTACGTACGTAGTCAGTCGTGATG AATTAGAGCAGATAGAGGGGGAAAGGGTT AAACCCC >gf4 CGTAGTCAGTCTAGCTGATGTCGATGCTG >hgh5 CATGCTAGTCGTAGTCGTAGTCGATGCTT TTTTAAGGGAACCCCC >hgy3 CCCCGGGTTTGGGAAAAGGGGGGGGATAG

Replies are listed 'Best First'.
Re^2: Compare hash with arrays and print
by jwkrahn (Abbot) on Jul 12, 2010 at 22:12 UTC
    my %rhash = reverse %hash; my %fh; foreach my $num (keys %rhash)

    Since you only need the unique keys from %hash you only really need an array:

    my @keys = keys %{{ reverse %hash }}; my %fh; foreach my $num ( @keys )
      Correct. The code is basically equivalent. We both reverse the hash and then find the keys of that reversed hash. Making a named array @keys is actually an extra step. I suppose if we wanted to, the whole right hand side of the "my @keys" line could go into the foreach() statement but, that could be obtuse.

      I was trying to show the workings of the reverse in the most straightforward way possible (simple syntax). I updated post to show the Op how to easily use Dumper to print the reversed hash, which is little more obvious how to do when it has an assigned name (rhash).