subrotuine正在获取散列引用:
sub test {
my $hash_ref = shift ;
if ( $hash_ref->{app} ) {
...
}
TheHash ref看起来像以下格式:如何找出它具有的数据类型
#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 }}]
如何处理此类数据结构
答案 0 :(得分: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 :(得分:1)
如果您提供参考,可以使用ref
检查类型:
my %hash = ( app => ['app1' ,'app2' ,'app3'] );
print ref($hash{app}), "\n";
打印ARRAY
。