in reply to Splitting long file

Hmmm. I'm sure I can work a ... in somehow:

open BIGFILE, $filename or die; while (<BIGFILE>) { if (/(.+)$/ ... /^\$$/ && next) { if (defined $1) { open SMALLFILE, ">$1" or die; next } print SMALLFILE; next; } warn "Untested code is bad!"; } close BIGFILE;

Replies are listed 'Best First'.
Re: Re: Splitting long file
by matija (Priest) on Apr 08, 2004 at 10:25 UTC
    You made a classic mistake there: $1 stays set until the next successful match, not until the next regexp invocation.

    My take on the whole problem would be slightly more verbose:

    open BIGFILE, $filename or die "Could not open $filename:$!\n"; while (<BIGFILE>) { unless (defined($smallfile)) { $smallfile=$_; chomp $smallfile; open(SMALLFILE,">$smallfile") or die "Could not open smallfile $sm +allfile (referenced in $.): $!\n"; } elsif (/^\$$/) { close(SMALLFILE) || die "Could not close $smallfile:$!\n"; $smallfile=undef; } else { print SMALLFILE; } } close BIGFILE;
    Update: $filename should contain the name of the BIG file, of course.

      Too right! That oughta learn me.

      Rereading, I now see the approach of the OP. Perhaps (again untested):

      $/ = "\$\n"; open BIGFILE, yada yada or die; while (<BIGFILE>) { my ($filename, $guts) = split /\n/, $_, 2; open SMALLFILE, ">$filename" or die; print SMALLFILE $guts; close SMALLFILE; } close BIGFILE;
      or even
      use File::Slurp qw( write_file ); $/ = "\$\n"; open BIGFILE, yada yada; while (<BIGFILE>) { write_file(split /\n/, $_, 2); }
      I tried this with a smaller file, it seems to work. Great!

      One error appears though: "Name "main::filename" used only once: possible typo at matija.pl line 3."

      Is this something I need to solve? Thanks!