检查数据结构并忽略散列或数组

Check data structure and disregard if hash or array

我在一个数组中有一堆哈希。检查我的键和值时,我得到了预期的输出,除了一些特殊情况,因为它们指的是更多 Arrays/Hashes.

想想这样的事情:

@AoH = ( { 'husband' => "homer", 'wife' => "marge" },
         { 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
         { 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} }); 

我的函数遍历数组并显示我的键和值,如下所示:

 sub function(...){    
    print "$key => $value\n";
 }

husband => homer
wife => marge
people => ARRAY(0x6b0d80)
Bob => 24
Lukas => 37
vegetables => HASH(0x2570d38)
tomato => red
carrot => orange

现在我想访问我的键和值,但是当获取像 ARRAY 或 HASH 这样的值作为值时,我想忽略该散列而不打印它。

是否有某种方法可以只访问标量类型的值?

到目前为止我试过这个:

if ($value eq 'ARRAY') {
}
elsif ($value eq ref {}) {
}
else {
print "$key => $value\n";
}

但是,它最终打印的结果与上面完全相同,并且没有忽略其他数据结构。

对于像您这样的任意数据结构,您可以使用 Data::Traverse:

use warnings;
use strict;
use Data::Traverse qw(traverse);

my @AoH = ( { 'husband' => "homer", 'wife' => "marge" },
            { 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
            { 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} }); 

traverse { print "$a => $b\n" if /HASH/ } \@AoH;

输出:

wife => marge
husband => homer
Bob => 24
Lukas => 37
carrot => orange
tomato => red

以下演示代码未使用外部模块,仅供教育用途。

use strict;
use warnings;
use feature 'say';

my @AoH = (  { 'husband' => "homer", 'wife' => "marge" },
             { 'people' => [{'Bob'=> 24, 'Lukas'=> 37}] },
             { 'vegetables' => { 'tomato' => "red", 'carrot' => "orange"} });
             
drill_in( \@AoH );

sub drill_in {
    my $data = shift;
    
    if( ref $data eq 'ARRAY' ) {
        drill_in($_) for @$data;
    } elsif ( ref $data eq 'HASH' ) {
        while( my($k, $v ) = each %{$data} ) {
            (ref $v eq 'ARRAY' or  ref $v eq 'HASH') ? drill_in($v) : say "$k => $v";
        }
    }
}

输出

husband => homer
wife => marge
Lukas => 37
Bob => 24
tomato => red
carrot => orange