How to Embed Unix Commands in Perl
Perl is a computer programming language with extensive facilities for scripting and text manipulation. Perl programs get executed by an interpreter, so variables are dynamically typed. When writing a complex application it is useful to be able to invoke operating system commands so the programmer can concentrate on the core function of his code without having to re-implement from scratch functionality that is already provided by existing (and tested) operating system code. In particular, you can embed operating system commands when your Perl program is running on Unix.
Instructions
-
-
1
Marshal the arguments for the Unix command from the Perl code. The specific way of performing this step depends on the intended function of your Perl code. For example, for a program that creates a new directory under a given point in the filesystem hierarchy, include the following lines in your code:
#!/usr/local/bin/perl
#
$pointInFilesystem = $ARGV[0];
$nameNewDir = $ARGV[1];
The first command-line argument to your Perl application is the point where the new directory will get created; the second argument is the name the new directory will have.
-
2
Assemble the Unix command into a single string variable. For example, for the directory-creation application, include the following lines in your code:
$unixCommand = "mkdir $pointInFilesystem"."/".$nameNewDir
String variable "$unixCommand" contains a legal invocation to Unix's "mkdir" command.
-
-
3
Invoke the Unix command by using Perl's "system" command. For example, for the directory-creation application, include the following line in your code:
system($unixCommand);
When "system" gets executed, it will create a new process and instruct it to execute system's argument -- in this case to create a new directory. Your Perl program will resume when the process created by "system" exits. You can invoke any other Unix or shell command using "system."
-
1