Vijay
Vijay

Reputation: 67211

What's wrong with this statement in Perl?

print "$_", join(',',sort keys %$h),"\n";

It's giving me an error below:

Use of uninitialized value in string at missing_months.pl line 36.
1,10,11,12

this print statement is present in a for loop as below:

foreach my $num ( sort keys %hash )
{
        my $h = $hash{$num};
        print "$_", join(',',sort keys %$h),"\n";
}

Upvotes: 3

Views: 203

Answers (1)

Zaid
Zaid

Reputation: 37136

No need for the "$_". That line should be:

print join (',' , sort {$a <=> $b} keys %$h),"\n";

While the $_ is treated as the default iterator in for and foreach loops (see perlvar), you've already assigned the iterator variable as $num.

Here is how to use the $_ correctly in a single line:

print join(',', sort { $a <=> $b } keys %{$hash{$_}}),"\n" foreach keys %hash;

On a Side Note...

sort uses string comparison by default, meaning that '10' is deemed to come before '2'. It seems that you're dealing with months (perhaps?), which is why I've used the numerical comparison block { $a <=> $b }.

Upvotes: 14

Related Questions