in reply to Re^3: Print to specific line
in thread Print to specific line

I agree with Laurent. Using both is unnecessary.

Here's an adjusted version which only uses a hash and accounts for possible missing line numbers, which prevents the uninitialized warnings.

use 5.010; use strict; use warnings; use List::Util qw( max ); my %hash = ( 4 => 'The future is unknown.', 1 => 'The day before yesterday sucked.', 5 => 'Today is a good day.', 3 => 'Not much hope for tomorrow.', ); my $last = max keys %hash; for my $line ( 1 .. $last ) { say exists $hash{$line} ? $hash{$line} : ''; }

Replies are listed 'Best First'.
Re^5: Print to specific line
by GotToBTru (Prior) on Jun 23, 2015 at 19:01 UTC

    If, as I suspect, the OP does not want the numbers to print:

    use strict; use warnings; my (%hash); while (<>) { chomp; my ($text,$line) = $_ =~ m/(.+)(\d+)$/; $hash{$line} = $text; } print $hash{$_} . "\n" for (sort keys %hash)

    Since I use only the keys, no worries about missing line numbers.

    Usage:

    perl pm1.pl < input.txt > output.txt

    Update: I along with other respondents missed the fact that there could potentially be non-sequential line numbers in the data, and there might need to be blank lines created accordingly. Updated again to be a bit more perlish.

    use strict; use warnings; my (@array); while (<>) { $array[$2] = 1 if ($_ =~ m/(.+)(\d+)$/) } print defined $_ ? $_ . "\n" : "\n" for @array[1..$#array];
    Dum Spiro Spero