madM has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Im trying to run a code of mine .. but every time i run it i get the error
Use of uninitialized value in printf at aprende3.pl line 590
I know that the error occurs when in the hash of hashes $A->{$key}->{$key2} the program encounters a 0 as value in $key2.. how can i skip that warning? any help would be really appreciated
foreach my $key (@aminos) { print OUT $key,' '; foreach my $key2 (@aminos ) { printf OUT ("$forprint " , $A->{$key}->{$key2}); } } }

Replies are listed 'Best First'.
Re: handling printf 0 error
by Anonymous Monk on Apr 29, 2014 at 10:41 UTC

    TIMTOWTDI, it also depends on exactly which of the values you're trying to print is undef - since I can't tell from your post I'm going to guess it's $A->{$key}->{$key2}, but if not, you will need to adjust the tests in the code examples below accordingly.

    Solution 1: Disable those warnings altogether. Note that warnings can be useful in debugging, so this may not be the best unless you know what you're doing.

    # ... foreach my $key2 (@aminos) { no warnings 'uninitialized'; printf OUT ("$forprint ", $A->{$key}->{$key2}); } # ...

    Solution 2: Don't print at all if the value is not defined.

    foreach my $key2 (@aminos) { printf OUT ("$forprint ", $A->{$key}->{$key2}) if defined $A->{$key}->{$key2}; }

    Solution 3: Use the defined-or operator // to replace the undef value with the empty string. (Only available in Perl 5.10 and above)

    foreach my $key2 (@aminos) { printf OUT ("$forprint ", $A->{$key}->{$key2} // ''); }

    Solution 4: Skip the loop iteration entirely if the value is undefined. (similar idea to Solution 2)

    foreach my $key2 (@aminos) { next unless defined $A->{$key}->{$key2}; printf OUT ("$forprint ", $A->{$key}->{$key2}); }
      thankyou! that really helped!
Re: handling printf 0 error ( how can i skip that warning? Use of uninitialized value in printf )
by Anonymous Monk on Apr 29, 2014 at 10:31 UTC