-4

我正在尝试将存储在字符串中的表基本上转换为哈希数组。这是我的数据:

model                 |part_number   |type             |serial_number   |
----------------------|--------------|-----------------|----------------|
SCBE-MX-S             |750-031391    |CB               |ZV1111          |
SCBE-MX-S             |750-031391    |CB               |ZR1111          |
SCBE-MX-S             |750-031391    |CB               |ZV1111          |

如何将其放入哈希数组中?

所以基本上它看起来像

array 0
model => SCBE-MX-S
PartNumber => 750-031391
type => CB
serialNumber => ZV1111

array 1
......

到目前为止,这是我的代码。它工作得很好,但现在我需要转换为使用哈希数组而不是单个数组。

use strict;
use warnings;

my @data;
my @data_;
my @index_;

my $input = `lrm show -t=model,part_number,type,serial_number component\\(chassis_resource_name=wf-nashville\\)`;

@data=split(/\n/, $input);

foreach my $token (@data){
  @data_ = split(/\|/,$token);
  my %fields = (
    "model" => $data_[0],
    "partNumber" => $data_[1],
    "type" => $data_[2],
    "serialNumber" => $data_[3],
  );
  push @index_, \%fields;
}

use Data::Dump;
dd \@index_;

输出

 [
  {
    model => "25 records found.",
    partNumber => undef,
    serialNumber => undef,
    type => undef,
  },
  {
    model => "model                 ",
    partNumber => "part_number   ",
    serialNumber => "serial_number   ",
    type => "type             ",
  },
  {
    model => ("-" x 22),
    partNumber => "--------------",
    serialNumber => "----------------",
    type => "-----------------",
  },
4

1 回答 1

2

我很失望您似乎根本没有自己解决这个简单的问题,但是这会按照您的要求进行。

use strict;
use warnings;

my @data;

while (<DATA>) {
  my %fields;
  @fields{qw/ model PartNumber type serialNumber /} = /[^\s|]+/g;
  push @data, \%fields if $fields{PartNumber} =~ /\d/;
}

use Data::Dump;
dd \@data;


__DATA__
model                 |part_number   |type             |serial_number   |
----------------------|--------------|-----------------|----------------|
SCBE-MX-S             |750-031391    |CB               |ZV1111          |
SCBE-MX-S             |750-031391    |CB               |ZR1111          |
SCBE-MX-S             |750-031391    |CB               |ZV1111          |

输出

[
  {
    model => "SCBE-MX-S",
    PartNumber => "750-031391",
    serialNumber => "ZV1111",
    type => "CB",
  },
  {
    model => "SCBE-MX-S",
    PartNumber => "750-031391",
    serialNumber => "ZR1111",
    type => "CB",
  },
  {
    model => "SCBE-MX-S",
    PartNumber => "750-031391",
    serialNumber => "ZV1111",
    type => "CB",
  },
]
于 2013-06-12T17:13:18.507 回答