esz*_*k.k 2 arrays perl list hashmap data-structures
我有一个列表,其中包含一些连接的值.我需要使用列表中的键和值创建一个hashmap并合并在一起.但我真的不知道该怎么做.
输入:
my @in =(
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat');
Run Code Online (Sandbox Code Playgroud)
预期产量:
"{ $env => { $ver => [ $file1, $file2, ... ] } }"
Run Code Online (Sandbox Code Playgroud)
我试过这些:
(1)
my @sack_files = (
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat');
my $sack_tree = {};
my %hash=();
for( my $i=0; $i<scalar @sack_files; $i++){
my @array = split(/[\/]+/,$sack_files[$i]);
for(my $i=0;$i<(scalar @array)-1;$i++){
my $first = $array[$i];
my $second = $array[$i+1];
$hash{$first}=$second;
}
# merge
}
Run Code Online (Sandbox Code Playgroud)
(2)
use Data::Dumper;
my @sack_files = (
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat',
);
my $sack_tree = {};
my %hash=();
for( my $i=0; $i<scalar @sack_files; $i++){
my @array = split(/[\/]+/,$sack_files[$i]);
nest(\%hash,@array);
}
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,我得到一个错误,因为当循环变量i = 1时,键/值已经存在,所以可能我必须检查先前添加的键/值.但我真的不知道怎么做.我真的很感激任何想法.
只需使用push将新成员添加到哈希散列中的现有数组中.您必须取消引用数组引用@{ ... }.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my @sack_files = qw( mgenv/1_2_3/parent.dx_environment
mgenv/1_2_3/doc/types.dat
mgenv/1_2_3/doc/etc.dat
mgenv/4_5_6/parent.dx_environment
mgenv/4_5_6/doc/types.dat
u5env/1_2_3/parent.dx_environment
u5env/1_2_3/doc/types.dat
u5env/4_5_6/parent.dx_environment
u5env/4_5_6/doc/types.dat
);
my %hash;
for my $sack_file (@sack_files) {
my ($env, $ver, $file) = split m{/}, $sack_file, 3;
push @{ $hash{$env}{$ver} }, $file;
}
print Dumper \%hash;
Run Code Online (Sandbox Code Playgroud)
产量
$VAR1 = {
'mgenv' => {
'1_2_3' => [
'parent.dx_environment',
'doc/types.dat',
'doc/etc.dat'
],
'4_5_6' => [
'parent.dx_environment',
'doc/types.dat'
]
},
'u5env' => {
'4_5_6' => [
'parent.dx_environment',
'doc/types.dat'
],
'1_2_3' => [
'parent.dx_environment',
'doc/types.dat'
]
}
};
Run Code Online (Sandbox Code Playgroud)