in reply to Re^8: Merge hashes in specific format
in thread Merge hashes in specific format

Try googling and understanding "Perl declaration"

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re^10: Merge hashes in specific format
by ovedpo15 (Pilgrim) on Jan 12, 2019 at 23:30 UTC
    I do understand why it does not work (it tries to enter into a non-declared element). I just asking what would be the best way to solve it. I can always add non-existing data to $files_href when I declare it but it does not feel right. Anyway, thank you.

      Are you trying to do something like this?

      #!/usr/bin/perl # https://perlmonks.org/?node_id=1228412 use strict; use warnings; my $one = { data => { dir1 => { fileA => { pid => { 61781 => 1 }, total => 13 } +, fileB => { pid => { 61799 => 1 }, total => 12 } +, }, dir2 => { fileA => { pid => { 61439 => 1 }, total => 5 }, fileC => { pid => { 12345 => 1 }, total => 10 } +, }, }, total => { fileA => 18, fileB => 12, fileC => 10 }, }; my $two = { data => { dir3 => { fileA => { pid => { 616161 => 1 }, total => 6 } +, fileD => { pid => { 54321 => 1 }, total => 12 } +, }, dir4 => { fileA => { pid => { 1718 => 1 }, total => 2 }, fileE => { pid => { 15151 => 1 }, total => 3 }, }, }, total => { fileA => 8, fileD => 12, fileE => 3 }, }; sub combinemanyhashes { my $newhash = { data => { map %{ $_->{data} // {} }, @_ }, total => do { my %total; for my $href ( @_ ) { $total{$_} += $href->{total}{$_} for keys %{ $href->{total} // + {} }; } \%total; } }; return $newhash; } my $totalhashref = {}; $totalhashref = combinemanyhashes( $totalhashref, $one, $two ); use Data::Dump 'dd'; dd $totalhashref;
        Not quite but thank you for the reply. I have created the following sub:
        my ($name,$dirs,$final_href) = @_; my %data; foreach my $dir (@{$dirs}) { decode($dir."/".$name,%data); # will change name my $final_href = ( data => { ( %{$final_href->{data} },%{ $data{data} } ) }, total => do { my %total; for my $href ( $final_href->{total}, $data{total} ) { $total{$_} += $href->{total}{$_} for keys %{ $href->{ +total} }; } \%total; } ); }
        But it won't work because when I pass $final_href to this sub, it is empty, so it will fail "Can't use an undefined value as a HASH reference"
        . I tried to add:
        $files_href->{data} = (); $files_href->{total} = ();
        But it also does not work. it wants a real hash (because we do dereferencing with %{$final_href->{data}).
        Any ideas how to solve it?
      > I can always add non-existing data to $files_href when I declare it

      Try and see what happens

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice