[英]Storing data using array reference
我有一个文件看起来像这样
run Test3
run Test1
{
home/usera/aa/TestFile1
home/usera/aa/TestFile2
}
Test 1
{
Command1 Value
Command2 Value
}
Test2
{
Command4 Value
Command1 Value
Sleep 4
Command5 Value
}
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]],
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.