http://www.perlmonks.org?node_id=1209158

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

Hi all. Here's an odd one, to me anyway. I'm running a script to process very large XML files with embedded JSON. When I run it, the memory increases indefinitely (the file can be 100s of GB and the RAM usage reaches 25GB+). Boiling it down, I reach the below. If I remove the line marked "## THIS LINE", the memory remains static, but leave it in and it increases again. Adding in a load of undefs seems to make no difference. It's evidently leaving the hash array around, but I can't see how to 'free' it.

Why would accessing a non-existent hash value cause that, or of course even better how do I prevent it?! Thanks for any help...

use JSON; open(IN,"<:utf8","$ARGV[0]"); while(<IN>) { if (m!^\s+<text.*?>({[^\{\|].+})</text>!) { my $jt = $+; $jt=~s/\&quot;/\"/g; my $json = new JSON; my $jp = $json->allow_nonref->utf8->relaxed->decode($jt); my $c = $jp->{'claims'}; # "claims":{"P31":[{"mainsnak":{"snaktype":"value","property": +"P31","hash":"...","datavalue":{"value":{"entity-type":"item","numeri +c-id":5},...}... }...}], if (ref($c) eq 'HASH') { foreach my $ch (keys %$c) { if (ref($c->{$ch}) eq 'ARRAY') { foreach my $cg (@{$c->{$ch}}) { if (defined $cg->{'mainsnak'}->{'datavalue'}-> +{'value'}->{'notexist'}) {} ## THIS LINE } } } } } }

====================================================

UPDATE: Thanks to all the replies, I've worked it out now.

Points should go to tinita as the suggestion of use strict pointed me in the right direction. It turned out that, in some of the lines that my script reads, the value $cg->{'mainsnak'}->{'datavalue'}->{'value'} is a string, not a hash. It seems treating a string as a hash causes the memory growth. I fixed it with:

if (ref($cg->{'mainsnak'}->{'datavalue'}->{'value'}) eq 'HASH' && defined $cg->{'mainsnak'}->{'datavalue'}->{'value'}->{'notexist'}) {}

(Of course my code does plenty else besides this, but the principle of needing to check that a variable is indeed a hash before checking for a key is the main takeaway here.)