Access to the Shell

 < Day Day Up > 

Perl is useful for administrative functions because it has access to the shell. That means Perl can perform for you any process you might ordinarily perform by typing commands to the shell. To run Linux commands in your Perl programs, use the `` syntax. For example, the code in Listing 29.4 prints a directory listing.

Listing 29.4. Using Backticks to Access the Shell
 $curr_dir = `pwd`; @listing = `ls -al`; print "Listing for $curr_dir\n"; foreach $file (@listing) {      print "$file"; } 

NOTE

The `` notation uses the backtick found above the Tab key (on most keyboards), not the single quotation mark.


You can also use the Shell module to access the shell. Shell is one of the standard modules that comes with Perl; it allows creation and use of a shell-like command line. Look at the following code for an example:

 use Shell qw(cp); cp ("/home/httpd/logs/access.log", "/tmp/httpd.log"); 

This code almost looks like it is importing the command-line functions directly into Perl. Although that isn't really happening, you can pretend that the code is similar to a command line and use this approach in your Perl programs.

A third method of accessing the shell is via the system function call:

 $rc = 0xffff & system('cp /home/httpd/logs/access.log /tmp/httpd.log'); if ($rc == 0) {         print "system cp succeeded \n"; } else {         print "system cp failed $rc\n"; } 

The call can also be used with the or die clause:

 system('cp /home/httpd/logs/access.log /tmp/httpd.log') == 0          or die "system cp failed: $?" 

However, you can't capture the output of a command executed through the system function.

NOTE

Access to the command line is fairly common in shell scripting languages, but is less common in higher-level programming languages.


     < Day Day Up > 


    Red Hat Fedora 4 Unleashed
    Red Hat Fedora 4 Unleashed
    ISBN: 0672327929
    EAN: 2147483647
    Year: 2006
    Pages: 361

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net