Reputation: 371
I have part of the code (program which needs to calculate sum of open files on system for specified 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 "$open";
print "Number of open files for users:$opt_u[0]=$generic_acc_open**$opt_u[1]=$generic_acc_open\n;"
}
where opt_u
is argument for users specified on cli.
My problem is when i run a program (./proc_limit -u root jenkins
) i am getting output like this:
Number of open files for users:root=85**jenkins=85
;Number of open files for users:root=13**jenkins=13
I am trying to get output in one line, probably it is not possible because array is specified with arguments in this case two times(for two users). Is it possible with for/foreach loop or i should use something else to get output in one line like this:
Number of open files for users:root=85**jenkins=13
Upvotes: 0
Views: 71
Reputation: 10903
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";
Upvotes: 0
Reputation: 9520
You're currently trying to print out results for two different queries using the same variable, $generic_acc_open
.
You need to get the results for each user and store them separately. Here's one possible way to do it that will work for any number of users:
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";
Output:
Number of open files for users: anonymous = 5548 ** jenkins = 42 ** root = 0
Explanation:
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";
To print the total number of files, keep a tally of how many files are open and print it at the end of the line:
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";
Upvotes: 1