使用数组引用存储数据

时间:2013-06-27 12:29:10

标签: arrays perl hash reference

我的文件看起来像这样

ConfigFile实现

run Test3
run Test1

TestDir文件

{

home/usera/aa/TestFile1
home/usera/aa/TestFile2

}

TestFile1

Test 1
{
  Command1 Value
  Command2 Value
}

Test2
{
  Command4 Value
  Command1 Value
  Sleep    4
  Command5 Value
}

TestFile2

Test 3
{
  Command3 Value
  Sleep    4
}

Test8
{
 Command9  Value
  Command10 Value
  Sleep     2 
}

我想要做的是打开每个TestFile并读取它,然后将数据存储在{..}中 在具有Testname(ie.Test1,Test3)的键的Test哈希中,键的值将是带有测试的命令值对

任何人都可以帮助我。谢谢

2 个答案:

答案 0 :(得分:0)

我想知道您的数据文件格式是否已经任意决定?这是一个可怕的设计,只有当你被限制使用它时,你应该坚持使用它,比如第三方。如果您有选择,那么有许多已建立的数据文件格式,您应该只采用其中之一。 JSON目前当之无愧,并且excellent Perl modules可以从CPAN处理它。

如果您决定坚持使用原始设计,那么此程序将按照您的要求执行。

use strict;
use warnings;
use autodie;

my (%tests, $commands, $test);

for my $file (qw/ testfile1.txt testfile2.txt /) {
  open my $fh, '<', $file;
  while (<$fh>) {
    s/\s+\z//;
    if (/\{/) {
      $commands = [];
    }
    elsif (/\}/) {
      $tests{$test} = $commands if $test and @$commands;
      $commands = undef;
    }
    elsif ($commands) {
      push @$commands, [ split ' ', $_, 2 ] if /\S/;
    }
    else {
      $test = $1 if /(\S(?:.*\S)?)/;
    }
  }
}

use Data::Dump;
dd \%tests;

<强>输出

{
  "Test 1" => [["Command1", "Value"], ["Command2", "Value"]],
  "Test 3" => [["Command3", "Value"], ["Sleep", 4]],
  "Test2"  => [
                ["Command4", "Value"],
                ["Command1", "Value"],
                ["Sleep", 4],
                ["Command5", "Value"],
              ],
  "Test8"  => [["Command9", "Value"], ["Command10", "Value"], ["Sleep", 2]],
}

答案 1 :(得分:-1)

你可以编写自己的解析器,但是你不太可能玩得开心。如果您将数据文件转换为JSONYAML,那么您就可以毫不费力地将文件读入内存。

相关问题