http://www.perlmonks.org?node_id=697414


in reply to Replacing expression on certain line numbers

Another option is to use list for the line numbers. The algorithm scans only once through data file

# first read and numericaly sort the lines my @lines = sort {$a <=> $b} <>; # then loop over data on STDIN # and write it to STDOUT my $line = shift @lines; while (<>){ if ($.==$line){ s/foo/bar/g; $line = shift @lines; } print; }
then you could use it like filter on UNIX-like OS-es:
cat data | ./script index-file > result

Best regards

P.S. Code is not tested

Replies are listed 'Best First'.
Re^2: Replacing expression on certain line numbers
by shmem (Chancellor) on Aug 03, 2008 at 22:00 UTC
    cat data | ./script index-file > result

    To avoid the "useless use of cat award"

    ./script index-file < data > result

    ;-)

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re^2: Replacing expression on certain line numbers
by FunkyMonk (Chancellor) on Jul 14, 2008 at 15:32 UTC
    ++karavelov

    I didn't realise how deep the magic of <> was.

    perlop says:

    The <> symbol will return undef for end-of-file only once. If you call it again after this, it will assume you are processing another @ARGV list, and if you haven't set @ARGV, will read input from STDIN.

    Unless I state otherwise, all my code runs with strict and warnings