in reply to Re^2: Modifying order of a hash
in thread Modifying order of a hash

Ah yes, should have tested my code. The first error is because you defined %newfile_attachments twice. The second error goes away if you use this:

foreach $fn (values %file_attachments) {

In your example you don't have a key 'FirstNum' in the hash. Be prepared to see an error message "Use of uninitialized value..." because of this. If you have subhashes with no key 'FirstNum', then you have to test for that and do something sensible with those subhashes

Btw, the output of Dumper looks much better if you use Dumper(\%x) instead of Dumper(%x)

Replies are listed 'Best First'.
Re^4: Modifying order of a hash
by monaghan (Novice) on Sep 25, 2008 at 23:00 UTC
    That worked. Many thanks. Now I want to expand this a bit more by adding more values inside the hash:
    my %hash = ( '103496-1' => [{ 'CLVD' => '5678', 'COMP' => '1234', 'FD +' => '0010', 'Files' => [{'File' => 'text.txt', 'hash' => 'a538346ad3 +485'},{'File' => 'text2.txt', 'hash' => '237d97892376a'}] }] ); print Dumper(%hash); print "\n"; my %newhash; my $fn; foreach $fn (values %hash) { $newhash{$fn->{COMP}}= $fn; delete $fn->{COMP}; } print Dumper(%newhash); print "\n";
    this gives me the error and wrong output as:
    Pseudo-hashes are deprecated at hashofhash.pl line 18. Use of uninitialized value in hash element at hashofhash.pl line 18. Pseudo-hashes are deprecated at hashofhash.pl line 19. $VAR1 = ''; $VAR2 = [ { 'FD' => '0010', 'COMP' => 1234, 'CLVD' => '5678', 'Files' => [ { 'hash' => 'a538346ad3485', 'File' => 'text.txt' }, { 'hash' => '237d97892376a', 'File' => 'text2.txt' } ] } ];
    Any ideas?

      Well, you changed your HoH to a HoAoHoAoH. Naturally you can't use the same code anymore that was used to change the HoH. That you got a strange error message is because to perl it looked as if you wanted to use Pseudo-Hashes. Pseudo-Hashes are arrays that can be accessed as hashes, all Pseudo-Hashes have a hash-reference as first element.

      You could bring the program back to working order by changing $newhash{$fn->{COMP}}= $fn; to $newhash{$fn->[0]{COMP}}= $fn;. But that would drop any other values in the outermost array (not that there are any at the moment). The question is can you work with a HoAoHoAoH when you still have problems using a HoH ?

        True. This is getting messy so thats why I posted another message on this thread showing that I should keep the original hash and modify it rather than delete items. Any ideas? Much appreciated