Hayra
Hayra

Reputation: 466

How can i get that system command's return to variable?

I have a sample code like this :

#!usr/bin/perl -w
my $path = shift;
my $max_number_of_files = shift;
print("Changing directory to path $path $!" . "\n");
chdir($path) or die "Cant chdir to $path $!";
print("Counting files..." . "\n");
counting();
sub counting {
$counted = system("ls -1 | wc -l");
if ($counted > $max_number_of_files) {
print("You have more or equal files");
return 1;
}
else {
    print("$counted");
    print "You have less files";
    return 2;
}
}

But my value $counted i think not get the value which system command show to console. I checked it and it is always zero. How can i handle this ?

Upvotes: 0

Views: 198

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 208107

It is generally considered bad practice to parse the output of ls because filenames can contain newlines which make them span more than one line and and wc will count them more than once.

You could try this:

#!/usr/bin/perl
use strict;
use warnings;

my @files=<*>;
print scalar(@files)," files\n";

Also, in terms of portability, you will do better using Perl's built-in features, since ls and wc may not be available on some (e.g. Windows) machines.

Upvotes: 2

Logan Ding
Logan Ding

Reputation: 1771

The return value of system is the exit code of the process that you called by system, not the output of the process.

To get the process output, use:

chomp($counted = `ls -1 | wc -l`);

Upvotes: 0

Related Questions