robertb
robertb

Reputation: 21

Hash key not being deleted in Perl

In Perl, in what context could you do something like this:

delete $ALIGN{$rna}{$dnaB};
print qq[deleted $dnaB\n] if ! exists $ALIGN{$rna}{$dnaB}; 

and then not have the print statement execute? This is giving me a huge headache. Thanks!

Upvotes: 1

Views: 114

Answers (1)

ikegami
ikegami

Reputation: 385917

What you posted will delete the key.

$ perl -e'
   $ALIGN{$rna}{$dnaB} = "abc";
   delete $ALIGN{$rna}{$dnaB};
   print exists($ALIGN{$rna}{$dnaB}) ? qq[exists\n] : qq[doesn'\''t exist\n] ;
'
doesn't exist

The only case where it wouldn't is if %{ $ALIGN{$rna} } is a misbehaved magical variable (e.g. a misbehaved tied variable), but I strongly doubt that's the case.

What probably actually happened is that you recreated the variable in between the delete and the exists.

$ perl -e'
   sub foo { }
   $ALIGN{$rna}{$dnaB} = "abc";
   delete $ALIGN{$rna}{$dnaB};
   foo($ALIGN{$rna}{$dnaB}{foo});
   print exists($ALIGN{$rna}{$dnaB}) ? qq[exists\n] : qq[doesn'\''t exist\n] ;
'
exists

Upvotes: 4

Related Questions