in reply to Re: Sorting an array of hashes and filenames
in thread Sorting an array of hashes and filenames

Thanks for all the replies. Here is the code that I have but still prints out the hashes unsorted? Not sure why?
foreach my $file ( $fns ) { open(FH, $file) or die "Can't open '$file': $!"; binmode(FH); my $hash = Digest::MD5->new->addfile(*FH)->hexdigest; $file_hashes{$hash} = $file; } foreach my $hash ( sort {$file_hashes{$a} cmp $file_hashes{$b} +} keys %file_hashes ) { print "$hash $file_hashes{$hash}\n"; } } ------------Results--------------- 32e3d09e0c2ff94316410b1444fbbb37a file1.txt 123d087078b62487c1d4c02f4c943af09 file2.txt 3ddbadc770e1c25a91aa186d3b0595945 file3.txt a3ff6417e3b703604c400965330ea6612 file4.txt b78c8fafdb9a5d4df6b36dcd35c56f6aa file5.txt

Replies are listed 'Best First'.
Re^3: Sorting an array of hashes and filenames
by DStaal (Chaplain) on Jan 14, 2009 at 21:27 UTC

    That sorted it perfectly: Exactly as you told it to.

    By the hash values, not the keys. The values of the hash (as you've constructed it) are the filenames, and if you'll notice, those are precisely in order.

    Take out the {$file_hashes{$a} cmp $file_hashes{$b}}. It isn't what you want. (If you really want to put something there, put in {$a cmp $b}, but that's the default...

      actually I was trying to sort on the first column only (the hash values) not the file names. How do I just sort on the first column, but still print the hash and the file name but sorted based on the hashes. thanks for all the help once again

        Ok, we've got a problem of terminology here: You have a hash (perl) which contains keys and values. Your data is filenames and hashes of the files. The keys of your hash (perl) are the hashes (file) of your files. The names of the files are the values of the hash (perl).

        Here is your data structure:

        %file_hashes = ( $hash1 => $filename1, $hash2 => $filename1, );

        This means that keys returns ($hash1, $hash2). And that ($file_hashes{$hash1} eq $filename1).

        So, when you type sort { $file_hashes{$a} cmp $file_hashes{$b} } keys %file_hashes you are sorting your list of hashes (file) by the values of the hash (perl). Which are your filenames.

        You want to sort the list of hashes (file). Which is the keys of your hash (perl). Which is sort keys %file_hashes. Try it. It will work.

        Then go read perldata five or six times. It's not the best introduction to the subject (it's designed more as a reference), but it is thorough.