Perl Tutorial: never directly exe a command
Small tip. Many times, you don't just execute a command. You build a command line. Always set that to a variable. Mostly so that you can print it, or examine it in the debugger before you run the command.
When running a command, you have 4 ways of doing it.
Using open(), backticks, system() and fork/exec. Truthfully, I have never tested the mechanisms for performance. So I do not know if one is faster or more efficient than the other. In 10 years of programming perl, I have never done the classic C fork/exec pattern.
Back ticks are great when what ever happens, examining the returning string will indicate success or failure.
Using system is great when the output does not need to be examined, but you just need to know the return code.
Using open() is used when the output need to be processed just as with back ticks. But there might me more data than you want to place in a single string. Or you want to process the output on a line by line basis.
System is easy,
Back ticks are easier:
Open is a little more involved.
When running a command, you have 4 ways of doing it.
Using open(), backticks, system() and fork/exec. Truthfully, I have never tested the mechanisms for performance. So I do not know if one is faster or more efficient than the other. In 10 years of programming perl, I have never done the classic C fork/exec pattern.
Back ticks are great when what ever happens, examining the returning string will indicate success or failure.
Using system is great when the output does not need to be examined, but you just need to know the return code.
Using open() is used when the output need to be processed just as with back ticks. But there might me more data than you want to place in a single string. Or you want to process the output on a line by line basis.
System is easy,
my $cmd = "/bin/ls -l ${dir}";
die "bad things happen" if (system($cmd));
Back ticks are easier:
my $output = `$cmd`;Open is a little more involved.
open(fi, "$cmd|") || die("open ls failed");
while() {
#parse output
}
close(fi)

0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home