Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How to reorder a text file

by johngg (Canon)
on Jun 12, 2018 at 17:34 UTC ( [id://1216493]=note: print w/replies, xml ) Need Help??


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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1216493]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-25 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found