Is it possible to load records from a file straight into a hash please? The records are delimited with /begin and /end, and have a fixed order of content.
What I want is a hash populated like this:
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'
I can then go off and process the records in the hash etc.. (reason for the ‘slurped_record’ entry is later I want to add new keys to say London like, ‘country=England’ etc
hash_city{London}{Country}='England'
I’ve managed to achieve something that works by slurping instead of reading the file line-by-line. Matching on a /begin, building up a record ($rec.=$_), then matching on a /end and processing. It’s a bit messy and wondered if there was a more elegant Perl approach..
My code attempt so far is as follows:
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
Made a little program to show the other way around, advancing your process as well. ) Don’t know whether is’t elegant or not, but I suppose it gets the job done. )