Perl 我如何获得系统命令';让我们回到变量?
我有这样一个示例代码:Perl 我如何获得系统命令';让我们回到变量?,perl,return,system,Perl,Return,System,我有这样一个示例代码: #!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
#!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;
}
}
但是我的值$counted我认为没有得到系统命令显示给控制台的值。我检查过了,它总是零。如何处理此问题?系统的返回值是由系统调用的进程的退出代码,而不是进程的输出 要获取流程输出,请使用:
chomp($counted = `ls -1 | wc -l`);
通常认为解析
ls
的输出是一种不好的做法,因为文件名可以包含使其跨越多行的换行符,并且wc
将对其进行多次计数
你可以试试这个:
#!/usr/bin/perl
use strict;
use warnings;
my @files=<*>;
print scalar(@files)," files\n";
#/usr/bin/perl
严格使用;
使用警告;
我的@files=;
打印标量(@files),“files\n”;
另外,在可移植性方面,使用Perl的内置功能会做得更好,因为在某些(例如Windows)计算机上,
ls
和wc
可能不可用。无法修改Counter.pl第9行靠近“ls-1 | wc-l
”的标量赋值中的标量chomp。它给出了类似的错误。chomp做了什么?@Hayra Oops,括号的位置不正确,现在已修复。仅供参考,chomp
删除字符串末尾的新行符号。