【发布时间】:2012-03-17 09:45:09
【问题描述】:
是否可以将文件中的记录直接加载到哈希中?记录由 /begin 和 /end 分隔,并且具有固定的内容顺序。
我想要的是这样填充的哈希:
hash_city{London}{slurped_record}='/begin CITY London\n big\n England\n Sterling\n/end CITY'
hash_city{Paris}{slurped_record}='/begin CITY\n Paris\n big\n France\n Euro\n/end CITY'
hash_city{Melbourne}{slurped_record}='/begin CITY\n\n Melbourne\n big\n Australia\n Dollar\n hot\n/end CITY'
然后我可以开始处理散列等中的记录。(“slurped_record”条目的原因是稍后我想添加新的键来表示伦敦,例如“country=England”等
hash_city{London}{Country}='England'
我已经设法通过啜饮而不是逐行读取文件来实现一些工作。在 /begin 上进行匹配,建立一条记录 ($rec.=$_),然后在 /end 上进行匹配并进行处理。有点乱,想知道有没有更优雅的Perl方法..
到目前为止我的代码尝试如下:
use strict;
use warnings;
use Data::Dumper;
my $string = do {local $/; <DATA>};
my %hash_city = map{$2=>$1} $string =~ /(\/begin\s+CITY\s+(\w+).+\/end\s+CITY)/smg;
print Dumper(%hash_city);
__DATA__
stuff
stuff
/begin CITY London
big
England
Sterling
/end CITY
stuff
stuff
/begin CITY
Paris
big
France
Euro
/end CITY
stuff
/begin CITY
Melbourne
big
Australia
Dollar
hot
/end CITY
stuff
【问题讨论】:
-
你的 slurp 会生成两个文件内容的副本,最好写成
my $string; {local $/; $string = <DATA>;}。