0

目标已经为我设定了,但我不知道如何到达那里。提前道歉。

使用 Perl - 我将收到一个以字符分隔的文件(我可以指定其结构),我需要将其转换为类似 XML文件

<MyConfig>
   Active = yes
   Refresh = 10 min
 <Includes>
 <Include_Rule_1>
 Active = yes
 Match = /Foo [Bb]ar/
 </Include_Rule_1>
 <Include_Rule_2>
 Active = yes
 Match = /Baz.*/
<Include_Rule_2>
</Include>
<Exclude>
<Exclude_Rule_1>
Exclude = /Bim Bam/
</Exclude_Rule_1>
 </Exclude>
</MyConfig>

所以简而言之,它将类似于XML (各个值不被尖括号包围),具有 3 个不变的部分,但它们的深度总是未知的。

我可以使用 CPAN 库,但不喜欢,因为这个脚本需要在我无法访问或控制的单个服务器上运行。

有任何想法吗 ?首发指针 ? 提示或技巧?

对不起,我在这里迷路了。

4

2 回答 2

0

您可以像在这个入门示例中一样使用Template::Toolkit模块(您需要先解析输入文件以提供 HASH):

#!/usr/bin/env perl

use strict; use warnings;
use Template;
my $tt = Template->new;
my $input = {
    MyConfig_Active => "yes",
    MyConfig_refresh => "10 min",
    MyConfig_Include_Rule_1_Active => "yes",
    MyConfig_Include_Rule_1_Match => "/Foo [Bb]ar/"
};
$tt->process('template.tpl', $input)
    || die $tt->error;

template.tpl文件 :

<MyConfig>
   Active = [% MyConfig_Active %]
   Refresh =  [% MyConfig_refresh %]
 <Includes>
 <Include_Rule_1>
 Active = [% MyConfig_Include_Rule_1_Active %]
 Match = "[% MyConfig_Include_Rule_1_Match %]"
 </Include_Rule_1>
(...)
</MyConfig>

样本输出:

<MyConfig>
   Active = yes
   Refresh =  10 min
 <Includes>
 <Include_Rule_1>
 Active = yes
 Match = "/Foo [Bb]ar/"
 </Include_Rule_1>
(...)
</MyConfig>

请参阅http://template-toolkit.org/docs/tutorial/Datafile.html

于 2013-01-27T16:59:10.367 回答
0

一种选择是使用Config::General从您从解析的字符分隔文件的结果中填充的哈希生成这样的文件。可以使用 Config::General 轻松读取此文件以重新填充散列:

use strict;
use warnings;
use Config::General;

my %config = (
    Active   => 'yes',
    Refresh  => '10 min',
    Includes => {
        Include_Rule_1 => {
            Active => 'yes',
            Match  => '/Foo [Bb]ar/'
        },
        Include_Rule_2 => {
            Active => 'yes',
            Match  => '/Baz.*/'
        }
    },
    Excludes => { 
        Exclude_Rule_1 => { 
            Exclude => '/Bim Bam/'
        }
    }

);

my $conf = new Config::General();

# Save structure to file
$conf->save_file('myConfig.conf', \%config);

内容myConfig.conf

<Excludes Exclude_Rule_1>
    Exclude   /Bim Bam/
</Excludes>
Refresh   10 min
<Includes>
    <Include_Rule_1>
        Match   /Foo [Bb]ar/
        Active   yes
    </Include_Rule_1>
    <Include_Rule_2>
        Match   /Baz.*/
        Active   yes
    </Include_Rule_2>
</Includes>
Active   yes
于 2013-01-27T22:21:56.753 回答