Perl can be used to invoke other programs and mess with their input and output. The most straightforward way to do this is with the system function which takes a command line string (or an array of strings), and has the operating system try to run it (this makes the most sense in a Unix environment). System returns 0 when the program successfully completes, or on error the global variable $? should be set to an error description.
system(“mail nick < tmp.txt”) == 0 | die “system error $?”;
The file-open function can also be used to run a program — a vertical var (|) at the end of the filename runs the filename as a process, and lets you read from its output…
open(F, “ls -l |”); ## run the ls -l process, and name its
output F
while (defined($line = )) { ## read F, line by line
…
The same trick works for writing to a process — just put the vertical bar at the beginning. Writing on the file handle goes to the standard input of the process. On Unix, the mail program can take the body of an email message as standard input…
$user = “nick\@cs”;
$subject = “mail from perl”;
open(MAIL, “| mail -s $subject $user”);
print(MAIL, “Here’s some email for you\n”);
print(MAIL, “blah blah blah, ….”);
close(MAIL);
If a programmer ever uses this technique to send Spam email, then all the other programmers will hunt that programmer down and explain the tragedy of the commons to them before the traditional beheading. Also, when writing a CGI, it’s important that you control the sorts of strings that are passed to system functions like open() and system(). Do not take text from the user and pass it directory to a call to system() or open() — the text must be checked to avoid errors and security problems.