0

我有一个文件看起来像这样

配置文件

run Test3
run Test1

测试目录文件

{

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

}

测试文件1

Test 1
{
  Command1 Value
  Command2 Value
}

Test2
{
  Command4 Value
  Command1 Value
  Sleep    4
  Command5 Value
}

测试文件2

Test 3
{
  Command3 Value
  Sleep    4
}

Test8
{
 Command9  Value
  Command10 Value
  Sleep     2 
}

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

谁能帮帮我。谢谢

4

2 回答 2

0

我想知道你的数据文件格式是不是随意决定的?这是一个可怕的设计,只有当你被第三方限制使用它时,你才应该坚持使用它。如果您可以选择,那么有许多已建立的数据文件格式,您应该简单地采用其中一种。JSON 目前当之无愧地流行,CPAN 提供了出色的 Perl 模块来处理它。

如果你决定坚持你的原始设计,那么这个程序会按照你的要求做。

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]],
}
于 2013-06-27T14:16:44.367 回答
-1

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

于 2013-06-27T13:44:38.627 回答