Shaman
Shaman

Reputation: 3

Error when running a DOS command in CGI

I tried to run a simple copy of one file to another folder using Perl

system("copy template.html tmp/$id/index.html");

but I got the error error: The syntax of the command is incorrect.

When I change it to

system("copy template.html tmp\\$id\\index.html");

The system copies another file to the tmp\$id foler

Can someone help me?

Upvotes: 0

Views: 206

Answers (1)

simbabque
simbabque

Reputation: 54333

I suggest you use File::Copy, which comes with your Perl distribution.

use strict; use warnings;
use File::Copy;

print copy('template.html', "tmp/$id/index.html");

You do not need to worry about the slashes or backslashes on Windows because the module will take care of that for you.

Note that you have to set relative paths from your current working directory, so both template.html as well as the dir tmp/$id/ needs to be there. If you want to create the folders on the fly, take a look at File::Path.


Update: Reply to comment below.

You can use this program to create your folders and copy the files with in-place substitution of the IDs.

use strict; use warnings;
use File::Path qw(make_path);

my $id = 1; # edit ID here

# Create output folder
make_path("tmp/$id");
# Open the template for reading and the new file for writing
open $fh_in, '<', 'template.html' or die $!;
open $fh_out, '>', "tmp\\$id\index.html" or die $!;
# Read the template
while (<$fh_in>) {
  s/ID/$id/g;       # replace all instances of ID with $id
  print $fh_out $_; # print to new file
}
# Close both files
close $fh_out;
close $fh_in;

Upvotes: 3

Related Questions