Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress hash after insertion warning?

Tags:

perl

Use of each() on hash after insertion without resetting hash iterator results in undefined behavior, Perl interpreter: 0x13932010 at /srv/data203806/MUXmh-Migration/Newperl/localperl/lib/site_perl/5.18.1/x86_64-linux-thread-multi/forks.pm line 1736.

Everything in my code is working fine but I'm getting this error. How can I suppress this warning?

like image 880
Naghaveer R Avatar asked Dec 20 '22 16:12

Naghaveer R


1 Answers

This warns:

use strict;
use warnings;
use Data::Dumper;

my %h = (a=>1);
while (my ($k,$v) = each %h) {
   $h{b} = 2;
}

print Dumper \%h;

This silences the warning:

use strict;
use warnings;
use Data::Dumper;

my %h = (a=>1);
{
   no warnings qw(internal);
   while (my ($k,$v) = each %h) {
      $h{b} = 2;
   }
}

print Dumper \%h;

Note the warnings category to silence is called internal. How did I know this? Do I have some kind of amazing memory for Perl's warnings categories? No. All Perl's error and warnings messages are well documented in perldiag; for each warning, it mentions the category it belongs to.

That said, this warning is telling you about a real problem. The behaviour of your code is undefined; if you switch to a different version of Perl, it may suddenly start acting differently. Better than switching off the warning would be to fix your code!

In my example above, a quick fix would be to use each to loop through a copy of %h rather than %h itself.

use strict;
use warnings;
use Data::Dumper;

my %h = (a=>1);
{
   my %tmp = %h;
   while (my ($k,$v) = each %tmp) {
      $h{b} = 2;
   }
}

print Dumper \%h;
like image 83
tobyink Avatar answered Mar 28 '23 10:03

tobyink