- 论坛徽章:
- 46
|
本帖最后由 zhlong8 于 2010-11-13 14:14 编辑
回复 14# yiten
写了个循环版的,FP用多习惯递归了  - use strict;
- use warnings;
- use Data::Dumper;
- sub a2h {
- my $array_ref = shift;
- my %hash;
- for my $item (@$array_ref) {
- my $hash_ref = \%hash;
- while (@$item > 2) {
- my $key = shift @$item;
- if (exists $hash_ref->{$key} and ref($hash_ref->{$key}) eq 'HASH') {
- $hash_ref = $hash_ref->{$key};
- }
- else {
- $hash_ref->{$key} = {};
- $hash_ref = $hash_ref->{$key};
- }
- }
- my($key, $val) = @$item;
- $hash_ref->{$key} = $val;
- }
- \%hash;
- }
- print Dumper a2h [[1,2,3,4,5], ['a','b','c',4, 6], ['a', 'b', 2,3,4], [ 1, 2, 3,'b', 4],[1,'kk','afkd'],[1,'kk', 'afkd',2]]
复制代码 输出为- $VAR1 = {
- '1' => {
- 'kk' => {
- 'afkd' => 2
- },
- '2' => {
- '3' => {
- '4' => 5,
- 'b' => 4
- }
- }
- },
- 'a' => {
- 'b' => {
- 'c' => {
- '4' => 6
- },
- '2' => {
- '3' => 4
- }
- }
- }
- };
复制代码 |
|