In Perl, you can execute external commands using system() or “. However, system and “ does not redirect command output to console and this results people who runs your perl script can’t see it. This also make debug much harder. Perl does not have a build in switch that equals to batch scripts’ “@echo on”, however this can be worked around by creating a ExecuteCommand subroutine.
sub ExecuteCommand {
my $cmd= $_;
my @cmdoutput = `$cmd`;
for $line (@cmdoutput) {
print $line;
}
Now just change your code from system($command) or `$command` to ExecuteCommand($command) and you will see all command output are redirected to console.
En, good but …
I want to see the command that it’s running
Just add print following line prior the call of command.
print “Now running $cmd …n”;
or call your logging subrountine.
I want to know return code of $cmd
Use my $cmdexitcode = $? >> 8; to get the return code of $cmd and then add return $cmdexitcode; at the end of ExecuteCommand
I want to pass more than one command to ExecuteCommand
Try this version
sub ExecuteCommand {
@cmdlist = (@_);
my $cmd = join(” & “, @cmdlist);
my @cmdoutput = `$cmd`;
my $cmdexitcode = $? >> 8;
for $line (@cmdoutput) {
print $line;
}
return $cmdexitcode;
}
Now you should call ExecuteCommand like this when you want to pass more than one command.
push @cmdlist, $cmd1;
push @cmdlist, $cmd2;
push @cmdlist, $cmd3;
ExecuteCommand(@cmdlist);
And $cmd1, cmd2, cmd3 will be run in one context shell.
Leave a Reply
You must be logged in to post a comment.