2014-10-05 45 views
0

值I有(其需要计算的对系统打开的文件总和为指定的用户程序)的代码的一部分:打印仅一个的/所需的在/ foreach循环

for my $opt_u (@opt_u){ 
    my $generic_acc_open = `/usr/sbin/lsof -u $opt_u | /usr/bin/wc -l`; 
    chomp ($generic_acc_open); 
    #print "$open"; 
    print "Number of open files for users:$opt_u[0]=$generic_acc_open**$opt_u[1]=$generic_acc_open\n;" 
} 

其中opt_u为用户参数在cli上指定。

我的问题是,当我运行一个程序(./proc_limit -u root jenkins)我得到的输出是这样的:

Number of open files for users:root=85**jenkins=85

;Number of open files for users:root=13**jenkins=13

我想在一个一线得到输出,可能这是不可能的,因为在这种情况下数组被指定为参数两次(对于两个用户)。是否有可能与/ foreach循环或我应该使用别的东西在这样一行来获得输出:

Number of open files for users:root=85**jenkins=13

+0

放下'\ n'也许? – Sobrique 2014-10-05 09:07:31

回答

0
print "Number of open files for users:" ; 
for my $opt_u (@opt_u){ 
    my $generic_acc_open = `/usr/sbin/lsof -u $opt_u | /usr/bin/wc -l`; 
    chomp ($generic_acc_open); 
    print " $opt_u=$generic_acc_open"; 
} 
print "\n"; 
1

您目前正在试图打印出结果对于使用相同变量的两个不同查询,$generic_acc_open

您需要为每个用户获取结果并分别存储它们。这里是一个可能的方式做到这一点,会为任意数量的用户的工作:

print "Number of open files for users: ", 
    join(" ** ", 
     map { my $n = `/usr/sbin/lsof -u $_ | /usr/bin/wc -l`; 
       $n =~ s/\s+//g; 
       "$_ = $n" 
     } @opt_u), "\n"; 

输出:

Number of open files for users: anonymous = 5548 ** jenkins = 42 ** root = 0

说明:

print "Number of open files for users: ", 
    # join every member of the array with " ** " 
    join(" ** ", 
    # map applies the expressions within the braces to each member of the array @opt_u 
    # map produces an array as output, which is acted upon by the join function 
    map { 
     # get number of open files for user $_ 
     my $n = `/usr/sbin/lsof -u $_ | /usr/bin/wc -l`; 
     # remove whitespace from the answer 
     $n =~ s/\s+//g; 
     # print out the user, $_, and the number of open files, $n 
     "$_ = $n" } @opt_u), 
"\n"; 

要打印文件总数,记录打开多少文件并打印它在行尾:

my $sum; 
print "Number of open files for users: ", 
    join(" ** ", 
     map { my $n = `/usr/sbin/lsof -u $_ | /usr/bin/wc -l`; 
       $n =~ s/\s+//g; 
       $sum += $n; 
       "$_ = $n" 
     } @opt_u), "; total files: $sum\n"; 
+1

谢谢你的酷解释!例如 – klerk 2014-10-05 10:09:04

+0

如何为sumarized数字的打开文件添加一个更多值?像这样:my $ sum + = $ n; ? – klerk 2014-10-05 11:35:01