in reply to split one file into many on finding a new line

i have a blank line before every "create table"statement

Before reading the file, set the input record separator to "paragraph mode" (just like in awk).
local $/ = "";
Then when you do a read ($in = <HANDLE>) you will read a whole CREATE statement in one go.

Update: Noticed Grandfather's excellent reply. Main difference is that using an empty string for the separator does not require there to be exactly one blank line between, it means one or more blank lines.

Replies are listed 'Best First'.
Re^2: split one file into many on finding a new line
by smarter_aries (Novice) on Sep 15, 2008 at 07:44 UTC
    Hi All, Thanks for your feedback, I modified my script..it runs but does not split the files.
    #!/sw/perl5/1.1/bin/perl use strict; #use warnings; my $filename = "/home/smarter/tables/MyFileName0000"; local $/ = "\n\n"; my $temp_line; my $filehandle; #open (my $filehandle, '<', $filename ) || open ( INFILE, $filename ) || ( die "Cant read $filename: $!"); #while ( <$filehandle> ) { while ( $temp_line = <INFILE> ) { chomp; ++$filename; print "**** Open file $filename here\n"; print "$_\n"; print "**** Close file $filename here\n"; } #close $filehandle or die "Fail on close '$filename': $!"; close(INFILE);
    the output is :
    **** Close file 126 here **** Open file 127 here **** Close file 127 here **** Open file 128 here **** Close file 128 here **** Open file 129 here **** Close file 129 here **** Open file 130 here
    Please help!

      change this  while ( $temp_line = <INFILE> ) to this  while ( <INFILE> ) and it will work.

      Also, note that if you want the filenames to be generated as MyFileName00* you'll have to drop the path from your $filename variable.

        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