Reputation: 13423
I have the following snippet of code that I run as part of several jobs everyday:
system("cp $keyFile $destinationFile");
system("chown $userID $destinationFile");
system("chmod 400 $destinationFile");
The problem with the above code is that sometimes, very rarely, at least one of the above operations do not complete successfully and my job fails. While it is alright for the job to fail if one of the above operations fail I still want to avoid the failing one of the simple system commands.
So I have the following options:
File::Copy::copy
, chmod
, chown
instead of the system commands.system()
commands. This I have done but does not explain why it might fail.Is is better/safer to use Perl subroutines instead of system commands. My jobs will always run on an RHEL5 machine [never Windows].
Is there anything else that I can do here. How can I collect more information on what went wrong?
Update: File names or file paths will never contain spaces or weird characters. They will be from the set [a-zA-Z].
Upvotes: 0
Views: 391
Reputation: 129481
Yes, it's always better to use Perl native versions (File::Copy
and chmod()
).
Among many reasons:
Performance. Calling system()
forks off between 1 and 2 new processes (one for command and likely another one for shell) which is a heavy operation
Error checking. IO related system calls in Perl set a "$!"
error text variable when errors happen:
File::Copy::copy($source, $destination)
|| die "Failed to copy from $source to $destination. Error: $!\n";
Upvotes: 4