Reputation: 155
I'm trying to build a hash table using build that that read a list of files, and store each value to the hash, something like this: - open directory and list them in array - then open each file and get some value from each file and put them into has table with file name, total, pass, and fail to the hash table
#!/usr/bin/perl
use strict;
my $dir = "../result";
opendir(DIR, $dir) or die $!;
my %result = ();
while (my $file = readdir(DIR)) {
# We only want files
next unless (-f "$dir/$file");
# do something here and get some value from each file
$total = $worksheet->get_cell(0,1);
$pass = $worksheet->get_cell(1,1);
$fail = $worksheet->get_cell(2,1);
# Print the cell value when not blank
$total = $total->value();
$pass = $pass->value();
$fail = $fail->value();
%result = (
"name" => "$file",
"total" => "$total",
"pass" => "$pass",
"fail" => "$fail"
);
}
foreach my $key (keys %result) {
print "Key: $key, Value: $result{$key}\n";
}
When I run it through the forloop I get only last entry or last file on directory, how do I add and build hash that keeps track of all files with keys & value mentioned above.. thanks in advance..
Upvotes: 1
Views: 4500
Reputation: 501
Store what you want IN the hash:
Instead of:
%result = (
"name" => "$file",
"total" => "$total",
"pass" => "$pass",
"fail" => "$fail"
);
which replaces the entire hash every time, try something like:
$result{$file} = "$total $pass $fail";
In which case, the keys of the hash will be the file names, and the values concatenated strings of the other values.
You can also make the elements of the hash something more complicated, like an array holding those three values, or whatever you might need.
Upvotes: 1
Reputation: 67048
You only get the last value because you are overwriting the value of %result
each time through the loop.
It sounds like you want an array of hashes rather than a single hash. How about something like this:
my @results;
while (my $file = readdir(DIR)) {
...
my %file_result = (
"name" => "$file",
"total" => "$total",
"pass" => "$pass",
"fail" => "$fail"
);
push @results, \%file_result;
}
Upvotes: 1