Wednesday, June 18, 2008

Ways in which you can tap the output of a command using PERL

Here I mention different ways in which you can tap the output of a unix command executed in PERL script.

1. Using the system command :
Here is a snippet of code that can be used to get the list of files in latest-first order:
system("ls -t > /tmp/anyfile");
In this way, you can redirect the output of a command & then read the file. But thats two tasks, inefficient.

2. Using the back-quotes `` :
my @list_of_files = `ls -t`;
chomp @list_of_files;
In this example the output of the command "ls -t" is stored in the variable @list_of_files. However there are drawbacks using back-quotes, one of the major one I noticed is that if the command returns with error you can't know. One way to detect error is to check for the number of elements in @list_of_files. If the command errored out @list_of_files will not have any elements.

3. Using the pipe & open :
my $cmd = "ls -t";
open ( READ_PIPE, "$cmd |" ) or die "Unable to execute $cmd: $!\n";
my @cmd_output = <READ_PIPE>;
close READ_PIPE;
This is another way of executing commands, if the command is not executed your script dies with an error message.


There are more ways to do it in PERL, for example using open2, open3 and other advanced functions.

2 comments:

hindurevolution said...

my @list_of_files = `ls -t`;
chomp @list_of_files;
In this example the output of the command "ls -t" is stored in the variable @list_of_files. However there are drawbacks using back-quotes, one of the major one I noticed is that if the command returns with error you can't know. One way to detect error is to check for the number of elements in @list_of_files. If the command errored out @list_of_files will not have any elements.
suman: i think when it returns with error, then @lit_of_files will contain the error status (ex:256) what is your opinion about this vikas?

Viki said...

Firstly, thanks for the comments...

Actually when you use back quotes `` the output (stdout) of the command executed will be stored in the variable you are assigning.

So if you want to get the exit status (ex:256, etc) you need the system() function.

Read this post for clarification:
http://techdiary-viki.blogspot.com/2008/06/issue-with-backticks-perl.html

Comment more, thanks.