in reply to How to reorder a text file

An approach reading a line at a time rather than slurping the whole file.

use strict; use warnings; open my $inFH, q{<}, \ <<__EOD__ or die $!; Title 1 Line of text A Line of text B Title 2 Line of text C Title 3 Title 4 Line of text D __EOD__ my @groups; while ( <$inFH> ) { if ( m{^Title} ) { unshift @groups, [ $_ ]; } else { push @{ $groups[ 0 ] }, $_; } } while ( my $group = shift @groups ) { print @{ $group }; }

The output.

Title 4 Line of text D Title 3 Title 2 Line of text C Title 1 Line of text A Line of text B

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: How to reorder a text file
by AnomalousMonk (Archbishop) on Jun 12, 2018 at 19:32 UTC
    ... rather than slurping the whole file.

    But won't the  while ( <$inFH> ) { ... } loop end up reading the entire file into the  @groups array (actually an array-of-arrays or AoA) before it finishes? This is not what I think of when I think of "line-by-line" processing of a file. (Actually, it looks a lot like slurping! :)


    Give a man a fish:  <%-{-{-{-<