in reply to Hash ref assignment to array results in anomaly

Then don't do that.

Maybe you could explain what you want to happen instead? If you want to create a new copy of $switch_optional every time you come around the loop, maybe reinitialize $switch_optional at the top of the loop instead of having it in scope for the whole function. If you just want to add it once, just add it once, instead of every time around the loop. Maybe you don't even want to use a hash, but simply add the switches to your list. It's hard to tell without you telling us.

Also consider whether it's really necessary to post a wall of code and add "HERE" markers. You could have spent some time reducing that code so that it still exhibits the problem, but is so small that you don't need any more HERE markers.

Replies are listed 'Best First'.
Re^2: Hash ref assignment to array results in anomaly
by perlpal (Scribe) on Jul 24, 2009 at 12:11 UTC
    When the hash ref is added as an element to the array whose key is "optional" , the elements $VAR1->{'optional'}2, $VAR1->{'optional'}2 also get added to the array. I do not understand why.

    I apologise for posting the whole code. I thought that probably some other part of the code was effecting such behavior.

      The problem stems, as I already described, from your top-level declaration of $switch_optional. You're not initializing it there, so Perl initializes it to a hash reference when you first use it as a hash reference. As you never change the value of the reference, Perl keeps that value. You then push, in the loop, that reference onto your array. So Perl pushes that same value of the same reference to your array. Three times in total.

      If you reduce your program to the relevant part, you actually find out what parts are irrelevant and what parts are relevant. This is an important capability to have or to evolve, if you want to have any chance at succeeding to program. So please, show the effort and reduce your program to only the relevant parts.