First, I would name the hash according to what the values mean. Unfortunately the OP didn't tell that key piece of info. Then we could have wound up with something like: $meanful_name{$country}
I think a hash of array would be better here than a string as the value. This would among other things allow easy sorting of the values. They happen to be sorted in the example data, but sorting would be possible with an array.
With the HoA, there is not need to check if the key exists. Perl would create it automatically. In your code, you do have to be sure that the key exists or the concatenation will throw an error. I think a better way to accomplish that would be: $hash{$tmp[0]} //= ''; This is a new operator in Perl 5.10 that sets the hash value to '' if it is not already defined. That way we eliminate the "if/else" statement and the concatenate case becomes the only one.
In Perl, often constructs like $temp[0] wind up being strangely absent. That is because we can assign meaningful names right away with a list slice. Shown below. It is also possible to use "undef" as a left hand side value, like ($country,undef,$num) That is an alternate way of "throwing something away". Hope this helps.
#!/usr/bin/perl use strict; use warnings; my %country_hash; while (<DATA>) { next if /^(\s*(#.*)?)?$/; # skip blank lines and comments chomp; # lines that are not skipped remove new line character '\n' my($country,$number) = (split /:/)[0,-1]; # split line on column ' +:' push @{$country_hash{$country}},$number; } foreach my $country (sort keys %country_hash) { print "$country:", join (":",@{$country_hash{$country}}), "\n"; } =Prints China:2:2:70 Japan:6:10 Thailand:6 =cut __DATA__ China:wd:2 Japan:wd:6 China:sg:2 Japan:sg:10 China:kng:70 Thailand:kng:6
In reply to Re^2: Reading from text file
by Marshall
in thread Reading from text file
by sarath92
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |