When you want to capture output, use backticks
my $val = `ls -lrt`;
or
my $val = qx/ls -lrt/;
Ref: perlop | [reply] [d/l] [select] |
| [reply] [d/l] |
In your sample, $val will contain the return code from ls. Most system commands return 0 or undef on success, so your system("ls -lrt "); call is succeeding (I'm quite sure ls can fail; I just can't remember seeing it do so.).
As ikegami and andyford mentioned, using system is almost certainly not the best solution. For one thing, it uses a sub-shell, where using glob or opendir doesn't.
You could try something like this (see stat):
#!perl
use strict;
use warnings;
my @list = glob("*");
foreach(@list){
(my $dev, my $ino, my $mode, my $nlink, my $uid,
my $gid, my $rdev, my $size, my $atime, my $mtime,
my $ctime, my $blksize, my $blocks) = stat;
# do processing here
}
yeah, verily, an update
ikegami pointed out that system only uses a subshell if the command contains shell metacharacters. In any case, unless you need the data exactly as produced by ls, using the Perl functions is certainly more portable (Windows doesn't have ls), and possibly faster.
emc
At that time [1909] the chief engineer was almost always the chief test pilot as well. That had the fortunate result of eliminating poor engineering early in aviation.
—Igor Sikorsky, reported in AOPA Pilot magazine February 2003.
| [reply] [d/l] |
$val will contain the return code from ls.
[system] uses a sub-shell
One of those statments is necessarily false. If a shell is used, $val will contain the return value of the shell, not ls.
So does system use a shell? It depends. "If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing." Otherwise, no.
In this case? no. However, I still wouldn't use ls.
Some examples:
system('command foobar') # no shell
system('command "foo bar"') # shell
system('command', 'foo bar') # no shell
system('sort < file | uniq') # shell
| [reply] [d/l] [select] |