tags:

views:

91

answers:

3

On Unix, all these three generate the same result

system("top -H -p $pid -n 1");             #ver1
system("top", "H", "p $pid", "n 1");       #ver2
system("top", "-H", "-p $pid", "-n 1");    #ver3
  • What is the difference between ver2 and ver3?

  • Is there any reason I should use ver2 and ver3, and not ver1?

  • They do not even support piping the results, for example, are there any ver2 and ver3 equivalents of the following call?

    system("top -H -p $pid -n 1 | grep myprocess | wc -l");
    
+2  A: 

Quoth perlfunc for system:

Note that argument processing varies depending on the number of arguments. If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program given by the first element of the list with arguments given by the rest of the list. If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.

So if $pid is just digits, all are equivalent.

To interpolate results of an arbitrary shell command including pipes use qx and friends.

msw
+3  A: 

Even it looks same it is not same:

$ perl -e 'system("./test.pl -H -p $$ -n 1");system("./test.pl", "H", "p $$", "n 1");system("./test.pl", "-H", "-p $$", "-n 1");'
-H,-p,10497,-n,1
H,p 10497,n 1
-H,-p 10497,-n 1
$ cat ./test.pl 
#!/usr/bin/perl
$\="\n";
$,=",";
print @ARGV;

It is up to top implementation that it works same. Other applications may not work same.

Hynek -Pichi- Vychodil
+1  A: 

As a practical reason for using LIST, sometimes your command-line arguments contain spaces or other characters that would confuse your shell.

system("mplayer.exe", "--volume", "75",
       q[C:/Program Files/My Music Player/Music Library/The "Music" Song.mp3]);
mobrule