Issue
What's the difference in the below two cases for file creation.
open(DATA,">newfile.txt"); #1.using open function
close(DATA);
`touch newfile.txt`; #2.using touch command
Which one better and fast? Note: When both open function and touch command used in Perl scripts, and the consider its used for creating empty files.
Solution
The clear difference is that in the second case you are going out to the system. A shell is started which runs the command or the command runs via execvp
system call (depending on the arguments, see below). There is a lot going on, and a number of things can go wrong as well.
More importantly, there is really more to do. What if the file already exists? For one thing, open
will truncate it while touch
will only update timestamps. But you want a new file, so you need to check first anyway. What if this fails? You need to check. Thus this should be a little routine.
Then just write it all in Perl. There is no advantage in delegating such a simple job, only pitfalls.
Note: use three-argument open
open my $fh, '>', $file or ...
with all requisite checks. Then you also have a much nicer lexical (indirect) filehandle to work with.
Thanks to hek2mgi for comments and to ikegami for clarifying that qx may bypass the shell depending on arguments (what appears undocumented?)†, much like system does.
This can be checked, per hek2mgi comment, by strace -f script.pl
, where with qx(touch "NEW")
in the script we find the line
[pid 24332] execve("/bin/sh", ["sh", "-c", "touch \"NEWFILE\""], [/* ...
while there is no /bin/sh
in the output for qx(touch NEW)
(no quotes, no shell).
To note, qx
does accept an array (unmentioned in docs), which clearly gets interpolated. This is seen from output of strace -f
on qx(@cmd)
with @cmd = qw(ls -l > tt.out)
, which has
[pid 30773] execve("/bin/sh", ["sh", "-c", "ls -l > tt.out"], [/* ...
Then a shell runs if needed (this example) and not otherwise (qw(ls -l
)), as discussed above.
† But at this point (Oct 2022) I do find it in qx
docs, loud and clear and upfront
Answered By - zdim Answer Checked By - Timothy Miller (WPSolving Admin)