Urbs has asked for the wisdom of the Perl Monks concerning the following question:

Greeting Monks, This should be a simple question that I just cannot figure out. I have a command that dumps thousands of 6 line records to a file. The records are not separated by blank lines. The last line of each record is something like: Metadata: 1114890 All that I need to do is combine these six lines into one so that I can manipulate them. Any ideas?? Thanks for sharing your wisdom, Urbs

Replies are listed 'Best First'.
Re: Paragraph mode??
by ikegami (Patriarch) on Jul 21, 2009 at 16:13 UTC
    my @rec; while (<$fh>) { push @rec, $_; if (/^Metadata:/) { do_something_with_record(\@rec); @rec = (); } }
Re: Paragraph mode??
by Corion (Patriarch) on Jul 21, 2009 at 15:57 UTC

    Maybe just setting your "record separator" ($/) to Metadata: 1114890 will give you what you want? Otherwise, you will need to show a bit of code and a bit of representative data. Potentially two nested loops might also help, one outer loop to process the records and one inner loop to collect lines up to the next /Metadata/.

Re: Paragraph mode??
by kennethk (Abbot) on Jul 21, 2009 at 16:09 UTC
    A couple of possibilities come to mind:
    1. Since you know the record length, you could use an external counter and read them in, appending them to the end of the last record read:

      my $count = 0; my @records = (); while (<IN>) { if ($count) { $records[-1] .= $_; } else { push @records, $_; } $count = ++$count % 6; } print join("\n",@records);
    2. You could slurp the file and split on a pattern that matches the last line:

      my $content = do { local $/; <IN>; }; my @records = split /(?<=Metadata\: 1114890\n)/, $content;
    As well, I'm sure, as a multitude of other possibilities. Note that in both the above, the resulting records still contain all the original newlines.