tags:

views:

412

answers:

5

I have a problem with the system function. I want to store the system functions output to a variable.

For example,

system("ls");

Here I want all the file names in the current directory to store in a variable. I know that I can do this by redirecting the output into a file and read from that and store that to a variable. But I want a efficient way than that. Is there any way .

+5  A: 

No, you cannot store the values of the ls output , since system always execute the command as a child process , so try with backtick `command` which executes the command in the current process itself!

abubacker
thanks ! I understood .
karthi_ms
@abubacker - backticks does execute a child process.
martin clayton
Backticks execute the command in a child process and capture its output. If you want to execute the command in the same process, you use `exec` - but it will never return because the original Perl code is no longer running after turning the process over to the other command.
Dave Sherohman
A: 

The easiest way uses backticks or qx():

my $value = qx(ls);
print $value;

The output is similar to the ls.

Yoda
`echo` is a shell command, the Perl equivalents are called `print` and `say`.
daxim
+4  A: 

my answer does not address your problem, however, if you REALLY want to do directory listing, don't call system ls like that. use opendir(), readdir(), or while loop

eg

while (<*>){
  print $_ ."\n";
}

In fact, if its not a third party proprietary program, always try to user Perl's own functions

ghostdog74
+2  A: 

The official Perl documentation for the built-in system function states:

This is not what you want to use to capture the output from a command, for that you should use merely backticks or qx//, as described in "STRING" in perlop.

There are numerous ways to easily access the docs:

  1. At the command line: perldoc -f system
  2. Online at perldoc.perl.org.
  3. Search the web using google.

If you want each directory listing stored into a separate array element, use:

my @entries = qx(ls);
toolic
+3  A: 

As abubacker stated, you can use backticks to capture the output of a program into a variable for later use. However, if you also need to check for exceptional return values, or bypass invoking the shell, it's time to bring in a CPAN module, IPC::System::Simple:

use IPC::System::Simple qw(capture);

# Capture output into $result and throw exception on failure
my $result = capture("some_command"); 

This module can be called in a variety of ways, and allows you to customize which error return values are "acceptable", whether to bypass the shell or not, and how to handle grouping of arguments. It also provides a drop-in replacement for system() which adds more error-checking.

Ether