2012-01-09 123 views
0

比方说,你有一堆如下面包含行的文件:如何在文本文件中自动插入字段?

 
{yellow_forest_ant|monsters_insects:2|Yellow forest ant|forestant||5|||10|100|||2|2|15||insect|||||||||}; 
{small_rabid_dog|monsters_dogs:1|Small rabid dog|forestdog||6|||10|90|||2|2|||canine|||||||||}; 

而且你要插入的第5和第6场,其中一些新的内容,要看是什么现有的域之间三个字段是。

你会如何以自动化的方式做到这一点? 在现有文本文件的行内插入一些动态内容。

我的解决方案(在Perl):

while(<>) { 
    if (/\{(.+?)\};/) { 
    my @v= $1 =~ /([^\|\{\}]*?|\{\{.*?\}\})\|/g; 
    my @output= (@v[0..4], guessMonsterClass($v[1]), $uniques{$v[0]}, '',@v[5..24]); 
    print '{'.join('|',@output)."|};\n"; 
    } else { print; } 
} 

虽然我的解决方案有效,它不能很好地工作。 改进请!

+1

只需将大括号内的字符串拆分到'/ \ | /'中,更改结果数组的元素,将''''上更改的数组加入并输出。 – 2012-01-09 04:43:18

+1

为什么这个问题用'xml'标记?我没有看到与XML相关的内容。 – choroba 2012-01-09 08:34:22

回答

0

摆脱了花眨眼({};)的,命名字段(完整性,合理性):

 
F1|F2|F3|F4|F5|F6 
yellow_forest_ant|monsters_insects:2|"Yellow forest ant"|forestant||5 
small_rabid_dog|monsters_dogs:1|"Small rabid dog"|forestdog||6 

使用DBIDBD::CSV

my $dbh = DBI->connect('dbi:CSV:', "", "", { 
     f_dir  => "../data" 
     , csv_sep_char => '|' 
     , PrintError => 0 
     , RaiseError => 1 
    }); 

    my $sth = $dbh->prepare('SELECT * FROM monsters.txt'); 
    $sth->execute; 
    while(my @row = $sth->fetchrow_array()) { 
    print '|', join('|', @row), "|\n"; 
    } 

    $sth = $dbh->prepare("UPDATE monsters.txt SET F5 = F6 * 2 WHERE F4 = 'forestant'"); 
    $sth->execute; 

    $sth = $dbh->prepare('SELECT * FROM monsters.txt'); 
    $sth->execute; 
    while(my @row = $sth->fetchrow_array()) { 
    print '|', join('|', @row), "|\n"; 
    } 

输出:

 
|yellow_forest_ant|monsters_insects:2|Yellow forest ant|forestant||5| 
|small_rabid_dog|monsters_dogs:1|Small rabid dog|forestdog||6| 
|yellow_forest_ant|monsters_insects:2|Yellow forest ant|forestant|10|5| 
|small_rabid_dog|monsters_dogs:1|Small rabid dog|forestdog||6| 
1

如果输入不包含转义竖线,你可以只使用splitsplice

while (<>) { 
    if (/\{(.+?)\};/) { 
     my @v = split /\|/, $1, -1; 
     splice @v, 5, 0, guessMonsterClass($v[1]), $uniques{$v[0]}, ''; 
     print '{', join('|', @v), "};\n"; 
    } else { 
     print; 
    } 
} 

注-1使用的限制split保持空字段在结束。所有空白字段都被捕获,因此您不需要在print中添加额外的垂直条。