in reply to Re: Sort text by Chapter names
in thread Sort text by Chapter names

Another alternative that I often see used here is to calculate the position and length of each unit within the file as you are scanning through it looking for markers. Put the marker-name, position, and length into an array of hashes, then sort the array by name using a custom sort-function. Retrieve each chapter directly from the original file by seeking to the proper position and reading the calculated number of bytes. (If the length might also be huge, read and write it in chunks not-to-exceed a digestible buffer-size.)

Replies are listed 'Best First'.
Re^3: Sort text by Chapter names
by tybalt89 (Parson) on May 28, 2018 at 22:23 UTC

    For the fun of it ( and also to show you can seek on DATA )

    #!/usr/bin/perl # use strict; use warnings; my %chapters; my $previous = undef; my $buffer; my $max = 4096; while(<DATA>) { if( /^Chapter/ ) { $chapters{$_} = $previous = [ tell(DATA) - length, length ]; } elsif( defined $previous ) { $previous->[1] += length; } } use Data::Dump 'pp'; print pp \%chapters; print "\n\n"; for ( sort keys %chapters ) { my ($start, $length) = $chapters{$_}->@*; seek DATA, $start, 0; while( $length > $max ) { read DATA, $buffer, $max; print $buffer; $length -= $max; } read DATA, $buffer, $length; print $buffer; } __DATA__ Chapter One There were lots of monkeys here and they ate all the bananas... lots more text up to hundreds of words. Chapter Nine This chapter has probably 1000 words. Chapter Two Here is the text in the second chapter... Chapter Five Here is the text in the fifth chapter... every chapter is of differing length, some long some short.
Re^3: Sort text by Chapter names
by jimpudar (Pilgrim) on May 28, 2018 at 16:25 UTC

    This is an elegant solution. I do like it better than mine as it uses only half the disk space!

    This thread is a fantastic example of TMTOWTDI.



    A reply falls below the community's threshold of quality. You may see it by logging in.