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

Hi monks, I have a file x lines long. How can i put each line into a separate file with extension .line. e.g. 1.line 2.line etc
open (OUT, ">.line"); while (<>) { print OUT $_; # increment file here }
thanks

Replies are listed 'Best First'.
Re: splitting output to separate files, one per line
by moot (Chaplain) on Feb 18, 2005 at 00:46 UTC
    You have an opportunity to learn more than a solution to your immediate problem here. What the other respondents have used is a special perl variable $. which holds the current line number of the file being read. Read more at perldoc perlvar.
Re: splitting output to separate files, one per line
by osunderdog (Deacon) on Feb 17, 2005 at 23:30 UTC

    use strict; while(<DATA>) { chomp; open FH, ">$..line"; print FH $_; close FH; } __DATA__ this is a file that will be split by line into files.


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

      Update: Nevermind, it works without the curlies. It didn't work a minute ago... The script probably didn't save correctly.

      Change
        open FH, ">$..line";
      to
        open FH, ">${.}.line";
      for your code to work.

Re: splitting output to separate files, one per line
by sh1tn (Priest) on Feb 18, 2005 at 00:24 UTC
    UNIX style:
    perl -ne 'open FH, ">$..line" and print FH $_ and close FH' data_file

    Dos style:
    perl -ne "open FH, '>', $..'.line' and print FH $_ and close FH " data +_file


Re: splitting output to separate files, one per line
by kprasanna_79 (Hermit) on Feb 18, 2005 at 09:11 UTC
    Hai
    This works for ur command line inputting of file to create 1.line and 2.line etc for each line of input file
    #!/usr/bin/perl use strict; use warnings; open(FIN,"< $ARGV[0]") || die "cant open file:$!"; while(<FIN>) { my $line = $_; open(FOUT,">$..line") || die "cant open file:$!"; print FOUT $line; close(FOUT); } close(FIN);

    --prasanna.k
Re: splitting output to separate files, one per line
by ambrus (Abbot) on Feb 17, 2005 at 23:58 UTC

    psed -n '=' inputfile | psed 's/.*/&w &.line/' | psed -nf - inputfile

    Update: this solution is probably good for only a few lines.