How can I store Perl's system function output to a variable?

63,374

Solution 1

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!

Solution 2

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 a while loop.

For example,

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

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

Solution 3

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.

Solution 4

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);

Solution 5

Use backticks to store output in a variable

$output = `ls`;
Share:
63,374
karthi_ms
Author by

karthi_ms

A True Techie :)

Updated on January 29, 2020

Comments

  • karthi_ms
    karthi_ms over 4 years

    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 .