The system() Function in Perl

PERLServer Side ProgrammingProgramming Scripts

You can use system() Perl function to execute any Unix command, whose output will go to the output of the perl script. By default, it is the screen, i.e., STDOUT, but you can redirect it to any file by using redirection operator > −

system( "ls -l")

When above code is executed, it lists down all the files and directories available in the current directory −

drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14
drwxr-xr-x 4 root root 4096 Sep 13 07:54 android
-rw-r--r-- 1 root root 574 Sep 17 15:16 index.htm
drwxr-xr-x 3 544 401 4096 Jul 6 16:49 MIME-Lite-3.01
-rw-r--r-- 1 root root 71 Sep 17 15:16
drwx------ 2 root root 4096 Sep 17 15:11 vAtrJdy

Be careful when your command contains shell environmental variables like $PATH or $HOME. Try following three scenarios −

$PATH = "I am Perl Variable";
system('echo $PATH'); # Treats $PATH as shell variable
system("echo $PATH"); # Treats $PATH as Perl variable
system("echo \$PATH"); # Escaping $ works.

When above code is executed, it produces the following result depending on what is set in shell variable $PATH.

I am Perl Variable
Published on 02-Dec-2019 15:13:21