in reply to Re: Global variable unexpectedly modified when passed by reference
in thread Global variable unexpectedly modified when passed by reference

Thanks for the clarification about the way the reference is used. The code I supplied is an example and in reality %hash would be the result of another sub call, so I can't pass by value. As I need to then call other subs with \%hash as an argument (some of which need to modify %hash), I'll need to find another way.

  • Comment on Re^2: Global variable unexpectedly modified when passed by reference

Replies are listed 'Best First'.
Re^3: Global variable unexpectedly modified when passed by reference
by parv (Parson) on Dec 08, 2014 at 15:27 UTC

    Of course you can pass by value & make changes sans changes to original reference via dereference ...

    #!/perl use warnings; use strict; use 5.010; my $got = throw_ref(); my %hash = change_hash( %{ $got } ); say 'original hash now ...'; show_hash( %{ $got } ); exit; sub change_hash { my ( %h ) = @_; say 'before modification ...'; show_hash( %h ); $h{'p'} += 10; $h{'q'} = 3; say 'after modification ...'; show_hash( %h ); return %h; } sub show_hash { my ( %h ) = @_; printf "%s : %s\n" , $_ , $h{ $_ } for sort keys %h; return; } sub throw_ref { return { 'p' => -2 } ; } __END__ before modification ... p : -2 after modification ... p : 8 q : 3 original hash now ... p : -2

    ... But if the hash reference is big and/or tied, then dereference could be expensive and/or undesired.

Re^3: Global variable unexpectedly modified when passed by reference
by GotToBTru (Prior) on Dec 08, 2014 at 15:15 UTC

    Sorry, this makes no sense. If the sub returns a reference to a hash, just dereference it and pass the hash. You can easily convert between scalar and reference. I suggest looking at this.

    1 Peter 4:10
Re^3: Global variable unexpectedly modified when passed by reference
by Anonymous Monk on Dec 08, 2014 at 15:29 UTC

    I don't understand why you can't pass by value, but no matter, you can just dereference inside the sub.

    sub mysub{ my $h = shift; my %dereferenced_hash = %$h; delete $dereferenced_hash{'b'}; }