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

In reply to Re: breaking a text file into a data structure -- best way? by rubasov
in thread breaking a text file into a data structure -- best way? by punkish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.