This will do as you ask. It uses File::Spec::Functions
to split each path into its components.
The first two elements of the hash are used directly as hash keys, relying on autovivication to create the necessary hash elements.
A simple push
to an implied array reference also autovivifies the lowest-level hash element.
I have used Data::Dump
to display the resulting hash. It is not part of the core Perl installation and you may need to install it, but it is much superior to Data::Dumper
.
use strict;
use warnings;
use File::Spec::Functions qw/ splitdir catfile /;
my @sack_files_1 = (
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat',
'u5env/1_2_3/parent.dx_environment',
'u5env/1_2_3/doc/types.dat',
);
my %paths;
for my $path (@sack_files_1) {
my ($p1, $p2, @path) = splitdir $path;
push @{ $paths{$p1}{$p2} }, catfile @path;
}
use Data::Dump;
dd \%paths;
output
{
mgenv => { "1_2_3" => ["parent.dx_environment", "doc\\types.dat"] },
u5env => { "1_2_3" => ["parent.dx_environment", "doc\\types.dat"] },
}