2010-11-11 51 views
1

一个subrotuine争论越来越哈希REF:如何找到哪种类型的传递给函数

sub test { 
    my $hash_ref = shift ; 

    if ($hash_ref->{app}) { 
    ... 

    } 

TheHash裁判的样子以下格式:如何找出它有什么类型的数据

#scallar 
$hash {app} = 'app' ; 
(or) 
#array 
$hash {app} = ['app1' ,'app2' ,'app3']; 
(or) 
#hash 
$hash {app} = { app1 => { type => 1, contact=> abc }} 
(or) 
#array +hash 
$hash {app} = [{ app1 => { type => 1, contact=> abc }} , 
       { app2 => { type => 2, contact=> ded }}] 

如何处理这种类型的数据结构

回答

2

看看这个:

use strict; 
use warnings; 

my $hash1 = {key => 'app',}; 
my $hash2 = {key => ['app1', 'app2'],}; 
my $hash3 = {key => {app1 => {type => 1, contact => 'abc'}},}; 
my $hash4 = {key => [{app1 => {type => 1, contact => 'abc'}}, {app2 => {type => 2, contact => 'ded'}}],}; 
my %tests = (1 => $hash1, 2 => $hash2, 3 => $hash3, 4 => $hash4); 

while (my ($test_nr, $test_hash) = each %tests) { 
    if (!ref $test_hash->{key}) { 
     print "test $test_nr is scalar\n"; 
    } elsif (ref $test_hash->{key} eq 'HASH') { 
     print "test $test_nr is hash ref\n"; 
    } elsif (ref $test_hash->{key} eq 'ARRAY') { 
     if (ref $test_hash->{key}[0]) { 
      print "test $test_nr is array of hash refs\n"; 
     } else { 
      print "test $test_nr is array\n"; 
     } 
    } 
} 
1

如果您提供参考,您可以使用ref检查类型:

my %hash = (app => ['app1' ,'app2' ,'app3']); 
print ref($hash{app}), "\n"; 

打印ARRAY

相关问题