[英]Storing data using array reference
I have a file looks like this 我有一个文件看起来像这样
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
}
what I want to do is open each TestFile and read it and just store the data within the {..} in a Test hash having key as Testname(ie.Test1,Test3) and value for the key would be the command value pair withing the test 我想要做的是打开每个TestFile并读取它,然后将数据存储在{..}中的Test哈希中,该哈希中的键为Testname(即Test1,Test3),并且该键的值是与考试
Can anyone help me out.Thanks 谁能帮我一下。谢谢
I wonder if your data file format has been decided arbitrarily? 我想知道您的数据文件格式是否是任意决定的? It is a dreadful design, and you should stick with it only if you are constrained to using it, say by a third party. 这是一个可怕的设计,只有在您限制使用它(例如第三方)的情况下,才应坚持使用它。 If you have a choice then there are many established data file formats and you should simply adopt one of those. 如果您可以选择的话,那么有很多已建立的数据文件格式,您只需采用其中一种。 JSON is deservedly popular at the moment and there are excellent Perl modules to handle it available from CPAN. JSON目前当之无愧地流行,并且有出色的Perl模块可以从CPAN获得处理它的功能。
If you decide to stick with your original design then this program will do what you ask. 如果您决定坚持原始设计,那么此程序将满足您的要求。
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;
output 输出
{
"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.