打印数组数组的散列内容

时间:2021-07-05 10:47:05

标签: perl

我一直在尝试在 Perl 中阅读以下结构:

my %Homes = (
          "Home 1" => [
          'TYPE_OF_HOUSE' => "Villa",
          'FIELD1' => ["1","2","3"],
          'Field2' => ["2","3","4"],
          'Field3' => ["3","4","5"],
      ],
      "Home 2" => [
          'TYPE_OF_HOUSE' => "Duplex",
          'FIELD1' => ["1","2","3"],
          'Field2' => ["2","3","4"],
          'Field3' => ["3","4","5"],
      ],
      "Home 3" => [
          'TYPE_OF_HOUSE' => "Apartment",
          'FIELD1' => ["1","2","3"],
          'Field2' => ["2","3","4"],
          'Field3' => ["3","4","5"],
      ],
  );

通过使用以下内容:

my @data_Array;
my ($inner_Key,$key,$names_ref);
foreach $key (keys %Homes)
 {
  print("Inner values of house $key are:");

  foreach $inner_Key ( @{$Homes{$key}})
   {
    if ($inner_Key != "TYPE_OF_HOUSE")
     {
      $names_ref  = \@$inner_Key;
      @data_Array = @{$names_ref};
      print($data_Array[0]);        
      print($data_Array[1]);      
      print($data_Array[2]);      
     }
    else
     {
      print($inner_Key);
     }
  }
}

我成功打印了:“Home 1”、“Home 2”,但是在尝试读取内部内容时,即使我使用了对数组的引用,也无法顺利进行。我错过了什么?我的目标是“识别”字段的类型,如果它是 TYPE_OF_HOUSE,那么只需打印它,因为它不是数组。否则,打印其数组的内部内容。

1 个答案:

答案 0 :(得分:3)

您必须使用 strictwarnings,因为它们会告诉您很多关于您的代码有什么问题的信息。

比较字符串时,您需要使用 ne 而不是 !=

您应该使用不同的数据结构,以便更轻松地访问内部数据元素。您有一个哈希数组,但作为哈希哈希更有意义。通过将 => 用于 'TYPE_OF_HOUSE' => "Villa",您已经欺骗自己相信这是一个哈希值。然而,它只是一个平面阵列。数组的第一个元素是TYPE_OF_HOUSE,第二个元素是Villa,第三个元素是FIELD1,第四个元素是一个数组引用,等等

use warnings;
use strict;

my %Homes = (
    "Home 1" => {
        'TYPE_OF_HOUSE' => "Villa",
        'FIELD1'        => [ "1", "2", "3" ],
        'Field2'        => [ "2", "3", "4" ],
        'Field3'        => [ "3", "4", "5" ],
    },
    "Home 2" => {
        'TYPE_OF_HOUSE' => "Duplex",
        'FIELD1'        => [ "1", "2", "3" ],
        'Field2'        => [ "2", "3", "4" ],
        'Field3'        => [ "3", "4", "5" ],
    },
    "Home 3" => {
        'TYPE_OF_HOUSE' => "Apartment",
        'FIELD1'        => [ "1", "2", "3" ],
        'Field2'        => [ "2", "3", "4" ],
        'Field3'        => [ "3", "4", "5" ],
    },
);

my @data_Array;
my ( $inner_Key, $key, $names_ref );
foreach $key ( keys %Homes ) {
    print("Inner values of house $key are:");
    print "\n";

    foreach $inner_Key ( keys %{ $Homes{$key} } ) {
        if ( $inner_Key ne "TYPE_OF_HOUSE" ) {
            @data_Array = @{ $Homes{$key}{$inner_Key} };
            print( $data_Array[0] );
            print "\n";
            print( $data_Array[1] );
            print "\n";
            print( $data_Array[2] );
            print "\n";
        }
        else {
            print($inner_Key);
            print "\n";
        }
    }
}

我使用 perltidy 来改进缩进。我添加了换行符以使您的 print 输出更易于阅读。