Home Scripting Perl Tutorial Running External Programs
Main Menu
System Verilog
Open Vera
Digital Concepts
Verification Basics
    - Perl Tutorial
        -- Perl Definition
        -- Syntax & Variables
        -- strings
        -- Arrays
        -- Associative Arrays
        -- If & While Loop
        -- File Input
        -- Print Output
        -- Strings and Regular Expressions
        -- Subroutines
        -- Running External Programs
        -- References
        -- Terse Perl
    - Bash
    - Makefile Tutorial
    - Perl Examples
    - Bash Examples
Interview Questions
Computer Architechture
C and C++
AsicGuru Blog
Tags Cloud
Usefull Sites
Know Your IP/Location
Local Information India
Buy Car/Inverter Batteries
Real Estate India
Sports Accessories India
Perl : Running External Programs
Share This Articale:

Running External Programs
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, ....");
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.


This Articles is written/submitted by puneet (Puneet Aggarwal). You can also contribute to Asicguru.com. Click here to start

Prev << Subroutines

Next >> References

Sign In
Login with :-
| | |  
  • Bookmark