Perl – 将文件从文件加载到哈希
发布时间:2020-12-16 06:16:53 所属栏目:大数据 来源:网络整理
导读:是否可以将文件中的记录直接加载到哈希中?记录以/ begin和/ end分隔,并具有固定的内容顺序. 我想要的是这样的哈希填充: hash_city{London}{slurped_record}='/begin CITY Londonn bign Englandn Sterlingn/end CITY'hash_city{Paris}{slurped_record}=
是否可以将文件中的记录直接加载到哈希中?记录以/ begin和/ end分隔,并具有固定的内容顺序.
我想要的是这样的哈希填充: hash_city{London}{slurped_record}='/begin CITY Londonn bign Englandn Sterlingn/end CITY' hash_city{Paris}{slurped_record}='/begin CITYn Parisn bign Francen Euron/end CITY' hash_city{Melbourne}{slurped_record}='/begin CITYnn Melbournen bign Australian Dollarn hotn/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 =~ /(/begins+CITYs+(w+).+/ends+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 解决方法
做了一个小程序来展示相反的方式,推进你的过程. )不知道是不是优雅与否,但我认为它完成了工作. )
my %city_record; ## we're going to process the input file in chunks. ## here we define the chunk start marker,and make Perl to separate file input with it local $/ = "/begin CITY"; # ignoring anything before the first section starts scalar <DATA>; while (<DATA>) { # throwing out anything after the section end marker # (might be done with substr-index combo as well,# but regex way was shorter and,for me,more readable as well ) my ($section_body) = m{^(.+)/end CITY}ms; # now we're free to parse the section_body as we want. # showing here pulling city name - and the remaining data,by using the split special case my ($city,@city_data) = split ' ',$section_body; # filling out all the fields at once # (may seem a bit unusual,but it's a simple hash slice actually,great Perl idiom) @{ $city_record{$city} }{qw/ size country currency misc /} = @city_data; } # just to test,use something of yours instead. ) print Dumper %city_record; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |