Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Troubles with simple parsing

by graff (Chancellor)
on Dec 19, 2004 at 03:34 UTC ( [id://415942]=note: print w/replies, xml ) Need Help??


in reply to Troubles with simple parsing

Some hints:
  • Check the "perlvar" man page to read about the "INPUT_RECORD_SEPARATOR" variable, "$/". You can set it to read each block of lines (up to the next blank line) instead of one line at a time, so each element of your "@all" array contains a full config record.
  • Look up the "split" function (perldoc -f split). After reading each block of lines into each array element, separate the lines ( split /\n/), then split each non-initial line into "attribute" and "value" ( split /=/).
  • You can load your array of hashes while reading the file, so you don't end up with two copies of the data in memory and you don't need to do repeated loops over the same set of data.

At the risk of short-cutting your exploration of the essential man pages, it could end up looking like this:

my @AoH_attribs; open( FILE, "<$file" ); { local $/ = ''; # empty string is "magic" for "paragraph-mode" while (<FILE>) # read a group of lines into $_ { my %hash = (); my $itemname = ( /^\[(.*?)\]/ ) ? $1 : 'NO_KEY'; next if ( !/=/ or $hashkey eq 'NO_KEY' ); $hash{item} = $itemname; for my $line ( split /\n/ ) { next unless ( $line =~ /=/ ); my ( $attrib, $value ) = split /=/, $line; $hash{$attrib} = $value; } push @AoH_attribs, { %hash }; # note use of curly braces } } close FILE; # now, @AoH_attribs contains a list of hash refs, one for each input b +lock; # you can access each hash like this: for my $itemref ( @AoH_attribs ) { my %itemhash = %$itemref; print "$_ = $itemhash{$_}\n" for ( sort keys %itemhash ); print "\n"; }
There are other ways as well.

(update: fixed syntax error in code)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://415942]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-19 13:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found