What are Data :: Dumper () side effects?

If I comment on Dumper($cmd_string) , then the while will never execute.

What side effects does Dumper () have on $ cmd_string?

Here is what $ cmd_string is before the subtitle:

 VAR1 = { 'The Java Runtime Library' => { 'apt-get install -y' => 'sun-java6-jre' } }; sub installPackages { my $cmd_string = shift; my %rc_hash; my $rc; Dumper($cmd_string); for my $desc (keys %{$cmd_string}) { while (my ($cmd, $arg) = each %{$cmd_string->{$desc}}) { print "system($cmd $arg)\n"; $rc = system("$cmd $arg"); if ($rc) { $rc_hash{$desc}{$cmd} = ''; } } } return \%rc_hash; } 

If I started the Perl debugger without Dumper () and used the x command in $ cmd_string, then it works, but if I just go through the code, it will not work.

This only happens after the code is completed at the end of the sub

  DB<3> x $cmd_string 0 HASH(0x2769550) '' => HASH(0x2769880) empty hash 'The Java Runtime Library' => HASH(0x25cc2a0) 'apt-get install -y' => 'sun-java6-jre' DB<4> x $cmd_string->{$desc} 0 HASH(0x2769880) empty hash 

Now, if I x $ cmd_string before the for loop, I get this at the end of the sub

 main::installPackages(msi.pl:1979): return \%rc_hash; DB<3> x $cmd_string 0 HASH(0x1125490) 'The Java Runtime Library' => HASH(0xf852a0) 'apt-get install -y' => 'sun-java6-jre' 
+7
source share
1 answer

each hash iterator uses a hidden variable for hashes to keep track of where it is in the hash. I assume that the code used to generate the hash of $cmd_string also uses each , but does not iterate to completion.

To reset each iterator, put keys %{$cmd_string->{$desc}}; before your while loop. Calling keys in a void context is the standard way to reset a hash iterator.

Alternatively, just use for my $cmd (keys %{$cmd_string->{$desc}}) { and then create the $arg variable inside the loop.

The reason why using Dumper() fixes the problem is because Dumper most likely calls keys on the hash, thereby dropping the iterator.

+12
source

All Articles