Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
perl a.pl > result.txt

my generated output:

name:asf192lin1	total slots used:0	total slots free:8	

name:asf192lin10	total slots used:7	total slots free:9	

name:asf192lin11	total slots used:6	total slots free:10	

name:asf192lin12	total slots used:8	total slots free:8	

name:asf192lin3	total slots used:0	total slots free:16	

name:asf192lin4	total slots used:8	total slots free:8	

name:asf192lin5	total slots used:8	total slots free:8	

name:asf192lin6	total slots used:8	total slots free:8	

How can i sum the evry rows and print the total at the end of the column using perl

What I have tried:

<pre>#!/usr/local/bin/perl
%namesum;
open(File,"tmp.txt")||die "error";
@array1=<File>;
close File;
open(File1,"<","gen_machines_data.txt")||die "error";
@file=<File1>;
foreach $line (@array1)
{
chomp $line;
}
foreach $line (@file)
{
$line=~s/[\{\}]//g; 
@parts=split(/\s+/,$line); 
@input=($slots_used,$slots_max)=split('/',$parts[2]);  
$name=substr($parts[0],0,11);
$namesum{$name}[0]+=$input[0]; 
$namesum{$name}[1]+=$input[1];
} 
$sum=0;
$total=0;
for $key (sort keys %namesum){
$slots_free = $namesum{$key}[1] - $namesum{$key}[0];
print "\nname:".$key."\t";
print "total slots used:".$namesum{$key}[0]."\t";
print "total slots free:".$slots_free."\t";
print "\n";
#$total+=$slots_free;
#print $total;
#$sum+=$input[0];
}
#print $sum;
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900