Is it possible to load records from a file directly into a hash, please? Entries are shared with / begin and / end and have a fixed order of content.
I want the hash to be populated as follows:
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'
Then I can leave and process the entries in the hash file, etc. (reason to write "slurped_record" later. I want to add new keys to say London, for example, "country = England", etc.
hash_city{London}{Country}='England'
I managed to achieve something that works by breaking out instead of reading the file in turn. Matching to / begin, creating a record ($ rec. = $ _), Then matching at / end and processing. It's a little messy and wondering if there was a more elegant approach to Perl.
My code attempt so far looks like this:
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
Chris source share