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

I experienced something this morning with the delete function that didn't seem to make sense. Here is the code in which the weirdness occurred:
my %subs = ( path => [ @{$session{hierarchy_path}} ] ); $subs{bottom_path_term} = ${pop(@{$subs{path}})}{term}; if (@{$subs{path}}) { delete $subs{path}[$#{$subs{path}}]{id}; } else { delete $subs{path}; }
Basically what is going on here is that I have an array of hashes that I want to manipulate without mutilating the orginal. The reference to the array is a value of one hash and I wanted to have a reference to the changed array be the value of another hash. (Maybe that's just a long way of saying that I wanted to make a copy of an array from one hash into a another hash.) Anyway, once I have a reference to the anonymous array, everything works as expected except the third line. Instead of deleting a key/value from the second hash (%subs), it deletes the key/value from the original hash (%session). I don't understand. If it was a problem with my dereferencing and referencing, I would expect pop to pop from the original hash but it doesn't. I used Data::Dumper to spew the structure of $session{hierarchy_path} both before and after this little snippet just to make sure I wasn't that crazy! Here's what it showed me:
Before: 'hierarchy_path' => [ { 'id' => 0, 'term' => 'Top of Hierarchy' }, { 'id' => '57000', 'term' => 'Education' } ], After: 'hierarchy_path' => [ { 'term' => 'Top of Hierarchy' }, { 'id' => '57000', 'term' => 'Education' } ],
Can anyone explain to me what's going on? BTW, I'm using Perl 5.6.1 on Linux

Replies are listed 'Best First'.
•Re: weirdness with delete
by merlyn (Sage) on Jun 26, 2002 at 18:18 UTC
      Thanks, I thought I was deep copying but after reading your article it seems that I'm not going deep enough. I'll try going deeper.
Re: weirdness with delete
by flounder99 (Friar) on Jun 26, 2002 at 19:49 UTC
    merlyn's right. You need to do a deep clone. Try using Storable's dclone. It should do a deep copy for you.
    use Storable qw( dclone ); my %subs = ( path => [ @{dclone($session{hierarchy_path})} ] ); #rest of script

    --

    flounder

Re: weirdness with delete
by Aristotle (Chancellor) on Jun 26, 2002 at 18:51 UTC

    I tried following your code and explanation and didn't manage anything but a headache. Post some dumps that illustrate your datastructures rather than explaining in words what your code does.

    Show me your flowcharts and conceal your tables.
    I shall continue to be mystified.
    Show me your tables, and I won't usually need your flowcharts;
    they'll be obvious.

    - Frederick P. Brooks, Jr., The Mythical Man-Month

    Makeshifts last the longest.