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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With