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

I have the problem. I would like to be able to automaticly generate many outfiles in .txt format in a forloop. Quite similar to when I write "program.pl >outfile.txt" in the command window, exept that now I have to generate many outfiles. Do you have an idea how to create the textfiles automaticly? Thanks for any help.

Replies are listed 'Best First'.
Re: Automatic generation of textfiles
by tirwhan (Abbot) on Feb 03, 2006 at 13:06 UTC

    I suggest you take a look at perldoc -f open and your questions should be answered.


    Dogma is stupid.
Re: Automatic generation of textfiles
by bart (Canon) on Feb 03, 2006 at 14:00 UTC
Re: Automatic generation of textfiles
by jonadab (Parson) on Feb 03, 2006 at 13:42 UTC

    tirwhan is right, but his link is taking forever to load, at least for me, so I'll add a little more information. Basically, you're looking for information on filehandles. You can open a file in output mode by doing something like open MYHANDLE, '>', $filename or die $!; and then you can write stuff to that open file with something like print MYHANDLE $stuff;

    To create multiple files, just do that repeatedly. Some wording in your question leads me to believe you already know a way to do something repeatedly.


    Sanity? Oh, yeah, I've got all kinds of sanity. Why, I've got so much sanity it's driving me crazy. In fact, I've developed whole new kinds of sanity.
Re: Automatic generation of textfiles
by idle (Friar) on Feb 03, 2006 at 13:31 UTC
    You can use exec or system: exec(':> $filename'); But be careful.

      While it's possible in shells to use exec to reopen descriptors, Perl's exec is a different beast. You'll either replace your running program with a very short lived shell, or you'll spawn a child shell which won't affect the parent process' file descriptors in any way.

        Maybe I get it wrong, but it seems to me that tamaguchi asked how to create files, not open.

      Huh?!? Low and behold I'd just point him to

      my %fh; open $fh{$_}, '>', $_ or die "Can't open `$_': $!\n" for @many_files; # if they're not TOO many ;-)