转换和打印哈希数组 - Perl

时间:2014-11-12 13:34:14

标签: arrays perl hash scalar

我真的不知道怎么做,所以我最终到了这里。

我想转换此输入:

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 $sack_tree_1 = {
    'mgenv' => {
        '1_2_3' => [ 'parent.dx_environment', 'doc/types.dat' ],
    },
    'u5env' => {
        '1_2_3' => [ 'parent.dx_environment', 'doc/types.dat' ],
    }
};

3 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题:

use strict;
use warnings;
use Data::Dumper;

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 %sack_tree_1;
foreach (@sack_files_1) {
    my ( $env, $number, @everything_else ) = split('/');
    push( @{ $sack_tree_1{$env}{$number} }, join( "/", @everything_else ) );
}

print Dumper \%sack_tree_1

答案 1 :(得分:1)

这会按照你的要求行事。它使用File::Spec::Functions将每个路径拆分为其组件。

哈希的前两个元素直接用作哈希键,依赖于 autovivication 来创建必要的哈希元素。

隐含数组引用的简单push也会自动生成最低级别的哈希元素。

我使用Data::Dump来显示结果哈希。它不是核心Perl安装的一部分,您可能需要安装它,但它优于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;

<强>输出

{
  mgenv => { "1_2_3" => ["parent.dx_environment", "doc\\types.dat"] },
  u5env => { "1_2_3" => ["parent.dx_environment", "doc\\types.dat"] },
}

答案 2 :(得分:0)

my $sack_tree_1 = {};
foreach my $data (@sack_files_1) {
    my @path = split '/', $data;
    my ($file,$last_part) = pop @path, pop @path; # get the file name and last part of the path
    my $hash_part = $sack_tree_1;
    foreach my $path (@path) { # For every element in the remaining part of the path
        $hash_part->{$path} //= {}; # Make sure we have a hash ref to play with
        $hash_part = $hash_part->{$path} # Move down the hash past the current path element
    }
    $hash_part->{$last_part} = $file; # Add the file name to the last part of the path
 }

这将处理2个或更多

的所有路径长度