Parsing a structured text file in Perl -



Parsing a structured text file in Perl -

i'm quite new perl , i'm having immense difficulty writing perl script parse structured text file.

i have collection of files this:

name: john smith occupation: electrician date of birth: 2/6/1961 hobbies: boating camping fishing

and on. field name followed colon, , info associated fields indented single tab (\t).

i create hash straight associate field contents field name, this:

$contents{$name} = "john smith" $contents{$hobbies} = "boating, camping, fishing"

or along lines.

so far i've been able field names hash themselves, i've not had luck wrangling field info form can nicely stored in hash. substituting/splitting newlines followed tabs won't work (i've tried, naively). i've tried rough lookahead create duplicate array of lines file , using figure out field boundaries are, it's not great in terms of memory consumption.

fwiw, i'm going through file line line, i'm not exclusively convinced best solution. there way parsing in straightforward manner?

reading file line line way go. here creating hash of array references. how read 1 file. read each file way , set hash of arrays hash of hashes of array.

#!/usr/bin/perl utilize strict; utilize warnings; utilize data::dumper; %contents; $key; while(<data>){ chomp; if ( s/:\s*$// ) { $key = $_; } else { s/^\s+//g; # remove whitespace force @{$contents{$key}}, $_; } } print dumper \%contents; __data__ name: john smith occupation: electrician date of birth: 2/6/1961 hobbies: boating camping fishing

output:

$var1 = { 'occupation' => [ 'electrician' ], 'hobbies' => [ 'boating', 'camping', 'fishing' ], 'name' => [ 'johnsmith' ], 'date of birth' => [ '2/6/1961' ] };

perl

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -