in reply to Re^3: split one file into many on finding a new line
in thread split one file into many on finding a new line

Thanks Kubrat, thanks all, I am able to separate the files now, code for the same as is as follows:
#!/sw/perl5/1.1/bin/perl use strict; my $filename = "MyFileName0000"; local $/ = "\n\n"; my $temp_line; my $filehandle; open ( INFILE, $filename ) || ( die "Cant read $filename: $!"); while ( <INFILE> ) { chomp; ++$filename; print "**** Open file $filename here\n"; open ( IFILE, ">>$filename" ); print IFILE "$_\n"; close(IFILE); print "**** Close file $filename here\n"; } select INFILE; close(INFILE);
but the files created are MyFileName0001,MyFileName0002 etc...is there a way i can have the file anme as the tabels name itself...i tried following:
#!/sw/perl5/1.1/bin/perl use strict; my $filename = "MyFileName0000"; local $/ = "\n\n"; my $scriptname; my $filehandle; open ( INFILE, $filename ) || ( die "Cant read $filename: $!"); while (<INFILE> ) { chomp; #++$filename; $scriptname=~ /CREATE TABLE ([\S]*)/; print "**** Open file $scriptname here\n"; open ( IFILE, ">>$scriptname" ); print IFILE "$_\n"; close(IFILE); print "**** Close file $scriptname here\n"; } select INFILE; close(INFILE);
But the scriptname is not being extracted properly..i am getting null.... Thanks

Replies are listed 'Best First'.
Re^5: split one file into many on finding a new line
by repellent (Priest) on Sep 16, 2008 at 02:55 UTC
    You can also write it as a one-line command:
    perl -00ne 'BEGIN { $filename = "MyFileName0000" } { open my $IFILE, " +>", $filename++; print $IFILE $_ }' table1.txt table2.txt tableN.txt

    • -00 means separate on empty lines (paragraph mode) -- see cdarke's reply
    • -n means implicit while (<ARGV>) { .. }
    • -e uses an expression as the program instead of a full-fledge script
    • The BEGIN { .. } block sets $filename at the beginning, outside of the implicit while loop
    • Creating an explicit scope { open my $IFILE, .. } means we do not have to explicitly close($IFILE) since $IFILE is only effective within the curly braces -- once out-of-scope, $IFILE is auto-closed

    To get a feel of the code, you can run this on its own:

    perl -MO=Deparse -00ne 'BEGIN { $filename = "MyFileName0000" } { open +my $IFILE, ">", $filename++; print $IFILE $_ }'