in reply to unexpected behavior on hash passed by reference

$ref = {}; # why won't this replace the underlying hash?

$ref is a scalar that holds a reference to a hash. {} creates a new anonymous hash, and you're overwriting the hashref with a reference to the new anonymous hash. In other words, you're just changing which hash $ref points to. To clear the hash pointed to by the reference, you need to dereference it: %$ref = (); will clear the hash pointed to by $ref (without removing the blessing).

Replies are listed 'Best First'.
Re^2: unexpected behavior on hash passed by reference
by perlfan (Parson) on Feb 26, 2022 at 18:47 UTC
    Amazing, I never considered using a dereference on the LHS of the assignment. What if I wanted to also remove the blessing? Thanks!
      What if I wanted to also remove the blessing?

      Sounds like an XY problem and/or that your example isn't really representative - why do you want to do this?

      Anyway, TIMTOWTDI:

      use warnings; use strict; use Data::Dump; sub one { $_[0] = {abc=>'one'}; } my $r1 = bless {r=>111}, 'One'; dd $r1; # bless({ r => 111 }, "One") one $r1; dd $r1; # { abc => "one" } sub two { my $ref = shift; $$ref = {abc=>'two'}; } my $r2 = bless {r=>222}, 'Two'; dd $r2; # bless({ r => 222 }, "Two") two \$r2; dd $r2; # { abc => "two" } sub three { my $ref = shift; return {abc=>'three'}; } my $r3 = bless {r=>333}, 'Three'; dd $r3; # bless({ r => 333 }, "Three") $r3 = three($r3); dd $r3; # { abc => "three" }

      And there's stuff like Acme::Damn, but I'm fairly certain that wouldn't be the right solution.

      > What if I wanted to also remove the blessing?

      I'm fairly sure there is some perldoc where Larry explains that - contrary to untie - he never saw any sense in implementing unbless ...

      Anyway you are always free to re-bless any object into a dummy class.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery