【问题标题】:Perl parsing hash of hashes of arraysPerl解析数组散列的散列
【发布时间】:2012-09-11 05:27:33
【问题描述】:

我正在尝试解析包含数组哈希值的 .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";
         }
    }
}

【问题讨论】:

  • 请显示您尝试过的代码,以便我们提出更改建议。
  • 您的代码有几个问题:首先,use warnings!其次,您正在将文件内容读入%VAR。使用warnings,您会收到“奇数个元素”警告。因为undef $` you slurp it all into the first key of %VAR. (What about your File::Slurp?). Try print Dumper \%VAR`,你会明白我的意思。请参阅@user5402's answer 了解如何完成。

标签: perl


【解决方案1】:

怎么样:

...
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";
    }
  }
}

【讨论】:

  • 谢谢你,我会试着了解你在这里做了什么,然后试一试。
  • 稍微解释一下就好了,这样 OP 就能看到问题出在哪里。
  • 你应该指出使用字符串eval的安全风险。
猜你喜欢
  • 2012-08-03
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2011-03-13
  • 2016-08-03
  • 2014-01-16
  • 2017-02-21
  • 2017-11-10
相关资源
最近更新 更多