在for / foreach循环中只打印一个/期望值

时间:2014-10-05 09:05:58

标签: perl

我有部分代码(程序需要为指定用户计算系统上打开文件的总和):

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

我试图在一行中输出,可能是不可能的,因为在这种情况下,数组被指定了两次参数(对于两个用户)。是否可以使用for / foreach循环或者我应该使用其他东西来输出一行如下:

  

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

2 个答案:

答案 0 :(得分: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 :(得分: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";
相关问题