开发者

Perl - Internal File (create and execute)

开发者 https://www.devze.com 2022-12-25 19:34 出处:网络
I have a quick question about creating files with perl and executing them.I wanted to know if it was possible to generate a file using perl (I actually need a .bat script) and then execute this file i

I have a quick question about creating files with perl and executing them. I wanted to know if it was possible to generate a file using perl (I actually need a .bat script) and then execute this file internally to the program. I know I can create files, and I have with perl, however, I'm wanting to do this internally to the program. So, what I want it to do is actually create a batch script internally to the program (no file is actually written to the disk, everything remains in memory, or the perl program), and then once it completes the writing of the file, I'd like to be able to actually ex开发者_StackOverflow中文版ecute this file, and then discard the file it just wrote. I'm basically trying to have it create a batch script on the fly, so that I can just have output text files from the output of the script, rather than creating the batch script on disk, then executing it, and then deleting the batch file from disk when its done.

Can this be done and how would I go about doing this?

Regards, Drew


Do you really need a batch script? Perhaps everything you want to do can be done directly from Perl or invoked directly by Perl via its system command.

If a batch script is essential, what's wrong with creating a temporary file for the script and then executing it with system? See File::Temp, which will even delete the temporary file automatically after you are done.

If the virtual-batch-file strategy is unavoidable, you might be able to leverage the /C and maybe /S options of cmd. Something like this:

use strict;
use warnings;

my @batch_commands = (
    'dir',
    q{echo "Make sure quoting isn't busted"},
    'ipconfig',
);

# Use & or &&, depending on your needs. Run `cmd /?` for details.
my $virtual_bat_file = join " &\n", @batch_commands;

system "cmd /C $virtual_bat_file";

But this feels very wrong. There has to be a better way to accomplish whatever the larger goal of your application is. By the way, when you run cmd /? to learn about /C, /S, and & vs. &&, you'll quickly appreciate how terrible it is in the Land of Batch. Stay away if at all possible.


open the file; create the contents; close the file; execute the file (with system(), for example); remove the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消