perl哈希嵌套和引用的使用
1.哈希的嵌套和引用
%hash = ( 'group1', {'fruit', 'banana', 'drink', 'orange juice', 'vegetable', 'cauliflower'}, 'group2', {'fruit', 'apple', 'drink', 'apple juice', 'vegetable', 'lettuce'}, 'group3', {'fruit', 'orange', 'drink', 'red tea', 'vegetable', 'tomato'}, 'group4', {'fruit', 'pear', 'drink', 'red wine', 'vegetable', 'cucumber'} ); for $key (sort keys %{hash}) { print "$key:\n"; my $ref=$hash{$key}; for $attr(sort keys %{$ref} ) { $Val=%$ref{$attr}; print "$attr\t\t$Val\n"; } print "\n"; }
输出结果
group1: drink orange juice fruit banana vegetable cauliflower group2: drink apple juice fruit apple vegetable lettuce group3: drink red tea fruit orange vegetable tomato group4: drink red wine fruit pear vegetable cucumber
2.数组的嵌套和引用
@fruit = ("banana","apple","orange","pear"); @vegetable = ("cauliflower","lettuce","tomato","cucumber"); @drink = ("orange juice","apple juice","red tea","red wine"); @list = ([@fruit],[@vegetable],[@drink]); $ref = $list[1]; for $attr1(@list) { print "@$attr1:\n"; for my $attr(@{$attr1}) { print "$attr\n"; } print "\n"; }
输出结果:
banana apple orange pear: banana apple orange pear cauliflower lettuce tomato cucumber: cauliflower lettuce tomato cucumber orange juice apple juice red tea red wine: orange juice apple juice red tea red wine
4556