从数组生成无序列表哈希

时间:2014-03-12 20:10:10

标签: arrays perl hash

我正在尝试使用哈希生成一个无序列表,我可以在jstree中进一步使用。但是这个数组只能从已经传递的数组中生成。

my @array = ( "New Order","Recurring Order","Previously Cancelled Order");

我希望输出看起来像

$data = {
         "New Order" => {
                         "Recurring Order" =>{
                                              Previously cancelled Order = 1
                                             }
                        }
    };

我可以简单地做

my $data{$array[0]}{$array[1]}{$array[2]} = 1

但是数组可以是n个变量,因此它变得有点复杂。我正在考虑递归,但我一直坐在这里,试图弄明白

2 个答案:

答案 0 :(得分:4)

这将生成您定义的数据结构。不知道你为什么要这样做。

my @input = ( "New Order","Recurring Order","Previously Cancelled Order");

my $data = 1;
$data = {$_ => $data} for reverse @input;

use Data::Dump;
dd $data;

如果您只是想让您的数组随机化,请使用List::Util;

use List::Util qw(shuffle);

my @newOrder = shuffle @input;

答案 1 :(得分:1)

sub recursive {
  my $v = shift @_;
  return @_>1 ? { $v => recursive(@_) } : { $v => @_ };
}

my @array = ( "New Order","Recurring Order","Previously Cancelled Order");
use Data::Dumper; print Dumper recursive(@array, 1);

输出

$VAR1 = {
      'New Order' => {
                       'Recurring Order' => {
                                              'Previously Cancelled Order' => 1
                                            }
                     }
    };