- Perl ›
- builtin functions ›
- here
system function - execute another process
You can use the system function to run another process.
system $cmd;
If the process ends successfully, 0 is returned as the return value. Error checking can be done as follows.
If you want to execute commands such as tar and gzip, you can use the system function.
Execute the ls command
As an example of the system function, let's execute the Linux ls command that displays the contents of the current directory.
I am using the or operator and die function for error checking.
my $cmd = 'ls'; system($cmd) == 0 or die "Can't execute $cmd:$!";
A list of current directories is displayed as shown below.
a.pl gperl module-starter.txt not_important_project ringowiki static-perl.tar batch Image-PNG-Simple mojo Object-Simple role task deal crontab.txt imager-japanese-translation.wiki mojo-examples
Pass arguments to system function
To pass arguments to the command you pass to the system function, pass the commands as an array to the system function. For example, if you want to pass the arguments "-l" and "tmp", write as follows.
my @cmd = ('ls', '-a', 'tmp'); system(@cmd) == 0 or die "Can't execute @cmd:$!";
System function security
The system function is a function that is prone to security problems. For example, suppose the input data from the web is "rm" and you pass it unchecked to the system function.
The system function executes an unintended command.
If you are receiving input from the user programmatically, make sure that the arguments you pass to the system function are safe.