Dear Monks,
My program uses a hash table to capture data, but for the same key there are several values in the input files. So I had to make two hash tables because there are two different values for the same key. It works. But I do not know how to generalise with three or more without having to use my %hash_3, my %hash_4, ... Could you check ? Thanks
Here is the code
#!/usr/bin/perl use strict; my $inFile = q{animals.txt}; open my $INFILE, q{<}, $inFile or die; my %hash; my %hash_2; while (<$INFILE>) { $_ =~ s/\s+$//; if (/^forest(\s+)(\w+)/){ my $country = $2; while (<$INFILE>){ chomp($_); if (/^-fox.*(\d\d\d\d)/){ chomp; my $fox_hour = $1; if (defined $hash{$country}){ $hash_2{$country}=$fox_hour; } else{ $hash{$country}=$fox_hour; } } last if (/monkey/); } } } close $INFILE; my $c_outfile = q{countries_results.csv}; open my $c_OUTFILE, q{>}, $c_outfile or die; my $c_inFile = q{countries_list.csv}; open my $c_INFILE, q{<}, $c_inFile or die; my $country; while (my $line = <$c_INFILE>){ my @Elements = split(";",$line); $country = $Elements[0]; $country =~ s/\s+$//; print $c_OUTFILE "$country;$hash{$country};$hash_2{$country}\n"; } close $c_INFILE; close $c_OUTFILE;
Here are the two input files
Here is the input file "animals.txt"
forest France -wolf -toad -fox 1350 monkey land -dog -cat -slug forest France -deer -swan -fox 1426 monkey forest USA -deer -swan -fox 1560 monkey
Here is "countries_list"
Italy USA France
And here are the output results
Italy;; USA;1560; France;1350;1426
In reply to add values with hash by steph_bow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |