tags:

views:

95

answers:

6

Can anyone give me an example on how I can call a shell command, say 'ls -a' in a Perl script and the way to retrieve the output of the command as well.

+3  A: 

Look at the open function in Perl - especially the variants using a '|' (pipe) in the arguments. Done correctly, you'll get a file handle that you can use to read the output of the command. The back tick operators also do this.

You might also want to review whether Perl has access to the C functions that the command itself uses. For example, for ls -a, you could use the opendir function, and then read the file names with the readdir function, and finally close the directory with (surprise) the closedir function. This has a number of benefits - precision probably being more important than speed. Using these functions, you can get the correct data even if the file names contain odd characters like newline.

Jonathan Leffler
+1  A: 

There are a lot of ways you can call a shell command from perl script, such as:

  1. back tick ls which captures the output and gives back to you.
  2. system system('ls');
  3. open

Refer #17 here: perl programming tips

thegeek
+1  A: 

Examples

  1. `ls -l`;
  2. system("ls -l");
  3. exec("ls -l");
Armando
A: 

You might want to look into open2 and open3 in case you need bidirectional communication.

miedwar
A: 

As you become more experienced with using Perl, you'll find that there are fewer and fewer occasions when you need to run shell commands. For example, one way to get a list of files is to use Perl's built-in glob function. If you want the list in sorted order you could combine it with the built-in sort function. If you want details about each file, you can use the stat function. Here's an example:

#!/usr/bin/perl

use strict;
use warnings;

foreach my $file ( sort glob('/home/grant/*') ) {
    my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
        = stat($file);
    printf("%-40s %8u bytes\n", $file, $size);
}
Grant McLean