tags:

views:

161

answers:

1
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";
}
+14  A: 

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 }.

Zaid
+1 First rate explanation!
drewk
there is a mistake here in your answer.You are right in saying that $_ is creating the problem.But i need the $num over here .So wht is did is istead of `print "$_", join(',',sort keys %$h),"\n";` i used `print "$num", join(',',sort keys %$h),"\n";`.this worked.
Vijay Sarathi
@benjamin : You know what you want...
Zaid