Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have multiple files in which I want to insert newline after every four lines. I know I can do it with sed but I want to do the same in perl. I have tried the following code:
use strict; use warnings; my @files= @ARGV; for my $input_file (@files) { system "sed -i '0~4 s/\$/\n/g' $input_file"; }
when I substitute it with any string it is done but when I am inserting newline as in above code it is giving error. I don't want to do it with sed as I know sed works only in linux. If someone can help me to insert a newline after every four lines using perl and not sed.

Replies are listed 'Best First'.
Re: put a newline character after every four lines in a file
by haukex (Archbishop) on Feb 24, 2017 at 06:27 UTC

    With a oneliner:

    $ perl -i -ple '$_.="\n" if $. % 4 == 0; close ARGV if eof' -- FILES

    Documentation: Command-line switches in perlrun, $. for the current line number, eof in regards to resetting $., and Multiplicative Operators for the modulo operator.

      Thanks...it works but when running in script with system command, it is giving errors....please suggest
        when running in script with system command

        What do you mean by this - are you running system("perl ... from inside a Perl script? That's not necessary, and a bit wasteful. How to best integrate the two depends on how you are further processing the files, so if you could explain and show an SSCCE, we could help you better.

        One way to do the same thing as the oneliner I posted above without calling another Perl process would be:

        { # new scope for local local *ARGV; @ARGV = @files; local $^I = ""; # -i command line switch while (<>) { print $_; print "\n" if $. % 4 == 0; close ARGV if eof; } }

        However, if you plan on further processing the files in the same script, this will be inefficient!

        Update: Fixed typo

        Update 2: Fixed this potential issue in the above example code.

        thanks alot...resolved the errors
Re: put a newline character after every four lines in a file
by shawnhcorey (Friar) on Feb 24, 2017 at 14:01 UTC

    Why are you using `sed` inside Perl? Perl can handle regular expressions.