I'd suggest a slightly different approach that has the advantage that one can read line by line so that there's no need to have all data in memory (which is nice if you've a lot of data).

#!perl use strict; my %data; my ($key, $data); while (<DATA>) { chomp($_); if (/^(\d+):\s*(.+)$/) { $data{$key} = $data if defined $key; $key = $1; $data = $2; } else { $data .= " $_"; } } $data{$key} = $data if defined $key; foreach my $key (sort {$a <=> $b} keys %data) { print "$key: '$data{$key}'\n"; } __DATA__ 3: Tag <test> found 1 Tag <test> found 2 5: Tag <test> found 3 7: Tag <test> found 4 14: Tag <test> found 5 16: Tag <test> found 6 18: Tag <test> found 7 21: Tag <test> found 8 25: Tag <test> found 9 27: Tag <test> found 10 29: Tag <test> found 11 32: Tag <test> found 12 34: Tag <test> found 13 49: Tag <test> found 14 80: Tag <test> found 15 98: Tag <test> found 16 Tag <test> found 17

Essentially, this is a finite state machine with two states, new-line and continue-line, represented by the if and the else part with the variable $key playing the role of state variable.

Essentially, this is a finite state machine with three states, initial, new-line and continue-line, the last two represented by the if and the else part with the variable $key playing the role of state variable distinguishing between the initial (undef) and the other two states.

(I modified the data slightly to be able to check that the data actually ends up with the right key in the hash.)

Hope this helps, -gjb-

Update: this explanation is more precise than the version I striked out.


In reply to Re: Matching over multiple lines in a scalar by gjb
in thread Matching over multiple lines in a scalar by Rich36

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.