in reply to Look Ahead regexp to insert line?

This should work:
#!/usr/bin/perl use warnings; use strict; open my $FH, '<', 'test.cfg' or die $!; my $pos; while (<$FH>) { $pos = $. if /echo.*install_list$/; # Remember the line numb +er. } die "Pattern not found.\n" unless $pos; $. = 0; # Reset the line number. seek $FH, 0, 0; # Start reading from the + beginning again. open my $OUT, '>', 'test.cfg.new' or die $!; while (<$FH>) { print {$OUT} $_; print {$OUT} "test\n" if $. == $pos; # After the remembered l +ine, print the extra text. } close $OUT; rename 'test.cfg.new', 'test.cfg';
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Look Ahead regexp to insert line?
by bowei_99 (Friar) on Oct 02, 2012 at 00:37 UTC
    Wouldn't using look ahead regular expressions be more efficient than going through the file letter by letter? That's what I was trying to do with the regexp in my post.

    -- Burvil

      My script goes through the file line by line, not letter by letter. It should work even for large files where stuffing everything into memory might be a problem.

      If you want to compare different solutions, benchmark. Benchmark can help you.

      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ