Search code examples
perlperl-data-structures

Variable has correct value but 'uninitialized value' warning is shown


There is a hash containing some data, whose users section is of my interest.

my %users = %{$data{'users'}};
foreach my $user_key (keys %users){
        print Dumper $users{$user_key};
        my $mailtime      =  $users{$user_key}{'mail_time'};
        my $id_local       =  $users{$user_key}{'id_local'};
        my $id_global      =  $users{$user_key}{'id_global'};
        print $mailtime;
}

everything works properly except the thrown warning at the line print $mailtime.
Even the print command would output a correct value along with the nonsense warning, as follows.

Use of uninitialized value $mailtime in print at custom_log.pl line 51.

The output of the dumper is:

$VAR1 = {                                                    
          'id_local' => '0',                                 
          'mail_time' => '1117579067',                       
          'id_global' => '2'                                 
        };

Solution

  • Without seeing a dump of %data it's impossible to see why it's failing, however a little testing suggests one of your users is missing the mail_time key. If I create %data as follow and run your script...

    my %data = (
        users => {
            user1 => {
                id_local  => '0',
                mail_time => '1117579067',
                id_global => '2',
            },
            user2 => {
                id_local  => '0',
                # purposely missing mail_time <---
                id_global => '2',
            },
        },
    );
    

    Then I get the same problem you are having... Output as follows

    Use of uninitialized value $mailtime in print at custom_log.pl line 27.
    1117579067