http://www.perlmonks.org?node_id=1228315

ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:

I have a function which looks as follows:
convertToFile($dir,$name,@data);
I had a hash that has files as keys and timestamps as values. But now I have changed the hash a little.
The keys of the new hash are directories and the values are the previous hash (meaning keys = files values = time).

hash before:
$newHash{$file} = $time;
hash after:
$newHash{$dir}{$file} = $time;
I were passing the hash keys as array to the convertToFile function:
convertToFile($dir,$name,sort(keys(%data)));
But now it won't work because I need the nested hashes.
I don't care about the order of the hashes I just care about the files.
I want to pass file to a the function and it does not matter from which directory.
I was wondering if its possible to do without any additional loops or code, maybe some special keywords.

Another related small question:
I were using the following syntax to combine two hashes into one:
%full = (%files1,%files2);
What if I have two keys (which are directories) that are the same? will it combine the inner hashes?

For example:
$files1 = { 'ABC' => { 'file1' => 6 'file2' => 5 'file3' => 8 } 'XYZ' => { 'file5' => 6 'file2' => 5 'file8' => 8 } }; $files2 = { 'ABC' => { 'file1' => 9 'file8' => 5 'file3' => 8 } };
How the new hash will look like?
Thank you

Replies are listed 'Best First'.
Re: how to get all keys of inner hashes
by 1nickt (Canon) on Jan 10, 2019 at 14:41 UTC

    Hi, you might like Hash::Merge.

    Hope this helps!


    The way forward always starts with a minimal test.
Re: how to get all keys of inner hashes
by Laurent_R (Canon) on Jan 10, 2019 at 15:02 UTC
    will it combine the inner hashes?
    No. Where hash items have the same key (ABC in your example), the items of the first hash will be removed and replaced by the corresponding elements of the second hash.

    But why do you ask, rather than testing by yourself?

Re: how to get all keys of inner hashes
by hippo (Bishop) on Jan 10, 2019 at 15:27 UTC
Re: how to get all keys of inner hashes
by choroba (Cardinal) on Jan 10, 2019 at 15:54 UTC
    You're passing just the keys to the function. Where do you get the times from? Please show more code, see SSCCE.
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      I don't care about the time, only the files (keys). Should pass an array of files.

        Depending on your ultimate goal then maybe a better structure would be

        $newHash{$file}{$dir} = $time;

        or use map

        #!/usr/bin/perl use strict; use List::MoreUtils qw(uniq); use Data::Dump 'pp'; my %files = ( 'ABC' => { 'file1' => 6,'file2' => 5,'file3' => 8, 'file4' => 4, }, 'XYZ' => { 'file2' => 5,'file5' => 6,'file8' => 8, }, ); my @files = uniq map {keys %{$files{$_}}} keys %files; pp \@files;
        poj