Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

system

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 .

like image 859
karthi_ms Avatar asked Mar 10 '10 10:03

karthi_ms


People also ask

How do you store the output of a command to a variable in Perl?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout: my $pid = 5892; my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`; print "not = $var\n"; This should do it.

What does system return in Perl?

Perl's System Command It returns 0 if the command succeeds and 1 if it fails. These return values are the inverse of most commands, which typically return 0 when they fail and 1 when they succeed.

What is QX in Perl?

PERL QX FUNCTION. Description. This function is a alternative to using back-quotes to execute system commands. For example, qx ls − l will execute the UNIX ls command using the -l command-line option. You can actually use any set of delimiters, not just the parentheses.

How do I run a perl command?

From Perl HowTo, the most common ways to execute external commands from Perl are: my $files = `ls -la` — captures the output of the command in $files. system "touch ~/foo" — if you don't want to capture the command's output. exec "vim ~/foo" — if you don't want to return to the script after executing the command.


1 Answers

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!

like image 55
abubacker Avatar answered Oct 04 '22 08:10

abubacker