簡體   English   中英

使用數組引用存儲數據

[英]Storing data using array reference

我有一個文件看起來像這樣

配置文件

run Test3
run Test1

TestDir文件

{

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(即Test1,Test3),並且該鍵的值是與考試

誰能幫我一下。謝謝

我想知道您的數據文件格式是否是任意決定的? 這是一個可怕的設計,只有在您限制使用它(例如第三方)的情況下,才應堅持使用它。 如果您可以選擇的話,那么有很多已建立的數據文件格式,您只需采用其中一種。 JSON目前當之無愧地流行,並且有出色的Perl模塊可以從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]],
}

您可以編寫自己的解析器,但是不太可能玩得開心。 如果將數據文件轉換為JSONYAML ,則可以輕松地將文件讀取到內存中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM