Perl 解析数组哈希的哈希

标签 perl

我正在尝试解析包含数组哈希值的 .dmp 文件。我需要从数组中获取键值对,以便将它们存储到 mysql 数据库中。我尝试了多种方法,但无法使其正常工作。

文件中的代码如下所示: 我需要在数据库中每行存储一个数组哈希

$VAR={  'booktodo-yzi07mwp-1102021083' => {
    '_modtime' => [
      1102021143
    ],
    'version' => [
      '25'
    ],
    'pubnum' => [
      '2332'
    ],
    '_status' => [
      'active'
    ],
    '_user' => [
      'lcm'
    ],
    'description' => [
      'Revise trademarks'
    ]
  },
  'booktodo-p8ekw9d3-1104950962' => {
    '_modtime' => [
      1104950986
    ],
    'version' => [
      '3.0'
    ],
    'pubnum' => [
      'S-2326-30'
    ],
    '_status' => [
      'active'
    ],
    '_user' => [
      'malz'
    ],
    'description' => [
      'Send out a request for install guide changes'
    ]
  },

这就是我到目前为止所拥有的。我只是想访问数组中的元素 谢谢!

#!/usr/bin/perl

use DBI;
use strict;
use Data::Dumper;
use File::Slurp;
use lib "$ENV{HOME}/modules/lib";

my %VAR;

#open DMP;
open (FILE, "<./booktodo.dmp") or die "could not open file: $!";
undef $/;


#store evaled data in %VAR hash
%VAR = <FILE>;
close(FILE);
eval %VAR;

foreach my $loop (keys %VAR){
    foreach my $hash (keys $VAR{$loop}){
         for my $i (0..$#{$VAR{$loop}}){
                print "$i= $VAR{$loop}[$i]\n";
         }
    }
}

最佳答案

怎么样:

...
my $contents = <FILE>;
close(FILE);

my $hash_of_hashes_of_arrays = eval $contents;
...

请注意,您现在正在使用对哈希的引用。 迭代它:

for my $key (keys %$hash_of_hashes_of_arrays) {
  my $hash = $hash_of_hashes_of_arrays->{$key};
  for my $key2 (keys %$hash) {
    my $array = $hash->{$key2};
    for my $i (0..$#$array) {
      print "$i: $$array[$i]\n";
    }
  }
}

关于Perl 解析数组哈希的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359147/

相关文章:

perl - Perl 中的生命游戏——从 C++ 翻译代码时出现问题

python - 组织数据

multithreading - 线程中的 Perl getstore

perl - LWP::UserAgent 无法使用 TLS1.1 发布

xml - 我如何使用 XML::LibXML 来解析使用 SAX 的 XML?

perl - Mechanize::Firefox 卡住了

bash - 当 Perl 嵌入到 shell 脚本中时,如何查看父脚本中用实际行号报告的语法错误?

perl - 需要解释在 Perl 中读取 "config"文件

Perl,如何从 Win32 和 Unix 上的 exec、system、open 函数获取线程的 pid

perl - 在 perl 中将文件句柄作为参数发送