输入文件(即happy.txt从happy开始生成)
NAME PEND RUN SUSP JLIM JLIMR RATE HAPPY
akawle 8 20 0 100 20:100 67980 71%
akumar6 16 0 0 100 100 0 0%
apatil2 2 4 0 100 10:100 20398 67%
ashetty 0 3 0 100 40:100 9725 100%
bdash 2 0 0 100 100 0 0%
gen_ls_data();
sub gen_ls_data{
my($lines) = @_;
my $header_found = 0;
my @headers = ();
my $row_count = 0;
my %row_data = ();
$lines = `happy`;
system("happy > happy.txt");
my $filename = 'happy.txt';
open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
print $fh $lines ;
close $fh;
foreach (split("\n",$lines)) {
if (/NAME\s*PEND/) {
$header_found = 1;
@headers =split;
next;
}
if ( $header_found == 0 ) { }
else {
if (/^\s*$/) {
$header_found=0;
next;
}
$row_data{$row_count++} = $_;
}
}
如何在不传递happy.txt
变量Linux命令的情况下将foreach
直接传递到$lines
循环?
答案 0 :(得分:1)
您似乎只需要$lines
来处理foreach
循环。
要么将它们作为传递给函数的参数
my ($lines) = @_;
# ...
# no need to run "happy" in any way or to deal with files
foreach (split /\n/, $lines) {
# ...
}
或将其作为happy
# no need for function arguments to contain $lines
my $lines = `happy`;
# no need for system() and reading the file
foreach (split /\n/, $lines) {
# ...
}
或使用重定向运行system
并从文件中读取
my $filename = 'happy.txt';
system ("happy > $filename");
open my $fh, '<', $filename or die "Can't open $filename: $!";
while (my $line = <$fh>) {
# process each line from the file
}
在这种情况下,您可以逐行阅读,而不是$lines
和split
。
您也可以使用反引号(qx operator),
my @lines = `happy`;
因为在列表上下文中它返回输出行的列表,而不是所有行的标量。
请注意,您应该为所有发送到系统的调用添加错误检查(而不仅仅是为了!)。 system如果运行正常,则返回零,因此您通常会执行类似
的操作system(...) == 0 or die "Can't fork: $!";
虽然错误上的qx
在标量上下文中返回undef
或在列表上下文中返回空列表,因此这些可用于初步检查问题。
他们还设置了您可以查询的$? variable以获取详细信息,请参阅system
和qx
的链接和链接。请注意,这首先涉及他们的操作,而不一定是他们执行命令的效果如何。