in reply to append line to previous line in txt file

How about:
do { $n = chomp; print; $_ = <>; print $/ x $n unless s/^;//; } while defined($_);
Works with empty files and files that begin with a ;

Update: This is just another way to think about the problem. You don't have to start every file reading loop with while (<>).

Update 2: Changed unless /^;/ to unless s/^;// which addresses concerns about it not working with consecutive lines beginning with a semi-colon.

Replies are listed 'Best First'.
Re^2: append line to previous line in txt file
by johngg (Canon) on Jul 09, 2008 at 10:29 UTC
    Your code doesn't seem to cope with consecutive lines starting with a semi-colon and it gets a bit noisy running with use warnings; against an empty file. The following seems to work.

    use strict; use warnings; my $acc; while ( <> ) { chomp; if ( m{^;} ) { $acc .= substr $_, 1; } else { print $acc, qq{\n} if defined $acc; $acc = $_; } } print $acc, qq{\n} if defined $acc;

    I hope this is of interest.

    Cheers,

    JohnGG

    Update: added defined to test to cope with lines that are empty. My test file is

    ;ddadadwaew sddjdsoeugfuiegf euefuefuerfefg ;erreuruyegfegr ueyrueuefeyr7e ; ; erieihir eiereyrgueyrgh ;ieruherueu ;ierhueryugr reieruyeruy
      Your code doesn't seem to cope with consecutive lines starting with a semi-colon
      I don't understand - I think it works just fine in that case. For example, on your test file the output is:
      ;ddadadwaew sddjdsoeugfuiegf euefuefuerfefg;erreuruyegfegr ueyrueuefeyr7e ;; erieihir eiereyrgueyrgh;ieruherueu;ierhueryugr reieruyeruy
      Did you get a different result?
        I think the difference between our solutions is that I remove the semi-colons because, apparently, that was also a requirement that was revealed in the CB.

        Cheers,

        JohnGG