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

Hello, I am trying to open a single file, & then split it into seperate text files like so...
------- filename.txt blahblah ------------- filename2.txt blahwahwah ------ etc..
So I made the code below, but it doesn't seem to create any new files, & I can't figure out why.
while(<>){ print if m/^-/; if (m/$\.txt/){ open (FILE, ">m/$\.txt/"); print FILE "Success"; close FILE; } }
Thanks in advance!

Replies are listed 'Best First'.
Re: File opening, based on a regex...
by Zaxo (Archbishop) on Feb 03, 2004 at 22:26 UTC

    You're misusing the regular espressions. Here is your read/write loop corrected to what I think you're looking for,

    while(<>){ print if m/^-/; if (m/^(\w+\.txt)/){ open (local(*FILE), "> $1") or die $!; print FILE "Success"; close FILE or die $!; } }
    That doesn't really split your file, it just prints "Success" over each .txt file mentioned in the one you read. To actually split, you need to tell perl how to spot the end of the file, while printing $_ to *FILE.

    Update: Ah, in that case I'll explain a bit more. The parenthesis in m/^(\w+\.txt)/ captures the matched text (here a number of 'word' characters followed by '.txt') and makes it available in the $1 variable. So 'foo.txt' at the start of the line matches, and $1 will contain that file name.

    I assumed a little different file format and intent than Plankton did. You should adjust what we say to fit your needs. Added some error checking.

    After Compline,
    Zaxo

      Yeah, I'm aware about the "Success" bit. I should've mentioned that tonight's the first time I've touched Perl, so trying to achieve each task little by little :D
Re: File opening, based on a regex...
by Plankton (Vicar) on Feb 03, 2004 at 22:20 UTC
    I think you want to do ...
    open (FILE, ">>$_");
    ... and don't forget to chomp ...
    while(<>) { chomp;

    Plankton: 1% Evil, 99% Hot Gas.