动态变量名和散列键

Dynamic variable names and hash keys

我用 Perl 编写的脚本解析结构如下的命令的文本输出:

Controller information
   Controller Status                     : Optimal
Logical device information
Logical Device number 1
   Logical Status                        : Optimal
Logical Device number 2
   Logical Status                        : Optimal

解析器应填充多维结构:

{
  "controller": {
    "Controller Status": "Optimal"
  }
  "logical": [
    {
      "Logical Status": "Optimal"
    },
    {
      "Logical Status": "Optimal"
    }
  ]
}

我尝试使用动态变量进行解析:

foreach (@lines) {
  $variable = "info{controller}" if (m/Controller information/);
  $variable = "info{logical}[]" if (m/Logical Device number (\d+)/);

  ${$variable}{1} =  if (m/\s+(.*?)\s+:\s(.*)$/);
}

在这种情况下,header 将设置与主题对应的散列键,并将所有后续参数放入所选键中。

第一个问题是,如果 $variable 包含任何哈希或数组键,动态 ${$variable} 将不起作用。有没有办法让动态变量与内部的哈希键一起工作?

第二个问题是动态变量被称为“always-a-bad-idea”,我想知道是否有简短但有效的方法来构建没有动态变量的解析函数?

使用 Data::DeepAccess (or Data::Diver 有点不同的界面)。

注意我用了 - 1作为索引,否则logical下索引为0的第一个元素是undef.

#!/usr/bin/perl
use warnings;
use strict;

use Data::DeepAccess qw{ deep_set };

my %info;

my @where;
while (<DATA>) {
    @where = ('controller')                 if /Controller information/;
    @where = ('logical', {index =>  - 1}) if /Logical Device number (\d+)/;

    deep_set(\%info, @where, "", "") if m/\s+(.*?)\s+:\s(.*)$/;
}

use Data::Dumper; print Dumper \%info;

__DATA__
Controller information
   Controller Status                     : Optimal
Logical device information
Logical Device number 1
   Logical Status                        : Optimal
Logical Device number 2
   Logical Status                        : Optimal

或者,使用引用:

#!/usr/bin/perl
use warnings;
use strict;

my %info;

my $where;
while (<DATA>) {
    $where = $info{controller}        if /Controller information/;
    $where = $info{logical}[  - 1 ] if /Logical Device number (\d+)/;

    $$where->{} =  if m/\s+(.*?)\s+:\s(.*)$/;
}
...