in reply to breaking a text file into a data structure -- best way?
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
|
|---|