Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

counting entries

Status
Not open for further replies.

uprichard

Programmer
May 2, 2002
16
I am reading data from a CSV file and after each read I end up with an array containing the data ie.

$array[0]="HTM"
$array[1]="complete"
$array[2]="1"

I want to be able to create variables that counts the number of times that a certain combination of data is returned. For the above I would want to add 1 to two different variables that are made up partly from the data returned from the read

status.$array[0].$array[1]
sev.$array[0].$array[2]


How do I do this in Perl?
 
The code below reads a csv that contains a number of lines ie.
"Agent","Complete","2"
"Agent","Complete","3"
"Agent","Open","1"
"Blar","Complete","2"

The first column is the name of a tool, second is the state and third is status.

What I need to do is to be able to is for each tool count the number of times that there is an entry for each type of state and each type of status.

Currently there are 30 tools, 5 states and 50 status values that could be reported (plus more could be added), so I dont what to have a load of if's etc



require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
my $column = '';
my @data;
# Open CSV file
open(CSVFILE, "test.csv");
# Loop until end of file
while (<CSVFILE>) {
if ($csv->parse($_)) {
# Split line into columns
my @field = $csv->fields;
my $count = 0;
$prod=$field[0];
$state=$field[1];
$severity=$field[2];
# Need to add 1 to correct part of array
$data[$prod][$state]++;
$data[$prod][$severity]++;
# Now lets see the values
print $data[&quot;Agent&quot;][&quot;Complete&quot;];
print &quot;\n&quot;;
print $data[&quot;Agent&quot;][&quot;1&quot;];
print &quot;\n&quot;;
} else {
my $err = $csv->error_input;
print &quot;parse() failed on argument: &quot;, $err, &quot;\n&quot;;
}
}
 
You should use a hash of hashes to keep track of this.

In the while loop:
$prod=$field[0];
$state=$field[1];
$severity=$field[2];
$tools{$prod}{$state}{$severity}++; # Increment count

After the while loop:
Code:
foreach $tool (sort keys %tools) {
    print &quot;data for tool $tool \n&quot;;
    foreach $state (sort keys %{ $tools{$tool} } ) {
        print &quot;\tstate=$state\n&quot;;
        foreach $severity (sort keys %{ $tools{$tool}{$state} } ) {
            print &quot;\t\tseverity $severity - $tools{$tool}{$severity} times \n&quot;;
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top