Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: breaking a text file into a data structure -- best way?

by rubasov (Friar)
on Apr 10, 2010 at 15:51 UTC ( #834009=note: print w/ replies, xml ) Need Help??


in reply to breaking a text file into a data structure -- best way?

To amend my stupidity yesterday, here's another approach by peeking into the next line:

use strict; use warnings; sub make_fh_peekable { my $fh = shift; my $eof = 0; my $buf; if ( eof $fh ) { $eof = 1; } else { $buf = <$fh>; } my $read = sub { return if $eof; my $rv = $buf; if ( eof $fh ) { $eof = 1; undef $buf; } else { $buf = <$fh>; } return $rv; }; my $peek = sub { return if $eof; return $buf; }; return $read, $peek; } my ( $ref, $key ); my ( $read, $peek ) = make_fh_peekable(\*DATA); while ( my $line = $read->() ) { if ( defined $peek->() and $peek->() =~ /^-{16}$/ ) { $key = 'a'; chomp $line; push @$ref, { $key++ => $line }; $read->(); } elsif ( $line =~ /^\*{16}$/ ) { if ( not defined $key ) { die "invalid input: got star line too early"; } ++$key; } else { if ( ref $ref ne 'ARRAY' or not defined $key ) { die "invalid input: got bare line too early"; } $ref->[-1]{$key} .= $line; } } use Data::Dump qw( pp ); pp $ref; __DATA__ title1 ---------------- title2 ---------------- foo title3 ---------------- foo **************** bar
p.s.: found japhy's much better implementation for the peeking: Peek.pm


Comment on Re: breaking a text file into a data structure -- best way?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2015-07-06 23:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (85 votes), past polls