in reply to How to reorder a text file

#!/usr/bin/env perl use strict; use warnings; my $txt = " Title 1 Line of text A Line of text B Title 2 Line of text C Title 3 Title 4 Line of text D "; my @reverse; my @normal = split /(Title \d)/, $txt; foreach my $n (0 .. @normal){ if ($n%2){ push @reverse, $normal[$n].$normal[$n+1]; } } chomp @reverse; @reverse = reverse @reverse; map { print $_."\n" } @reverse;

Replies are listed 'Best First'.
Re^2: How to reorder a text file
by AnomalousMonk (Archbishop) on Jun 13, 2018 at 12:00 UTC

    In the

    foreach my $n (0 .. @normal){ if ($n%2){ push @reverse, $normal[$n].$normal[$n+1]; } }
    loop, aren't you indexing beyond the end of the  @normal array? Won't this produce "Use of uninitialized value..." warnings if warnings are enabled? Shouldn't the loop range be  for my $n (0 .. $#normal-1) { ... } instead?

    (And BTW: Aren't you losing an opportunity to avoid using a foreach-loop by not re-writing the loop as a map | void-context map statement? :)


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