in reply to How to preserve values outside a sub

"This sub localises (using "my") ..."

As you've seen in multiple replies, that's not performing the localisation you were expecting. You can, however, get that behaviour with local. Here's a quick example to demonstrate that:

$ perl -E ' my $x = { a => 1 }; say $x->{a}; { local $x->{a} = 2; say $x->{a}; } say $x->{a}; ' 1 2 1

In general, I wouldn't do that; instead choosing one of the methods already shown, involving dereferencing the original hashref and creating a new one. There may be occasions, where you are working with very large data structures, and need to perform this operation many times (perhaps in a loop), that you run into efficiency issues; in these types of cases, especially when you only need to modify a small number of values, using local may be appropriate.

perlsub has a number of sections with information about local. In particular, see "Localization of elements of composite types" and "Localized deletion of elements of composite types".

Because I didn't see it mentioned in the linked documentation, I'll just point out that also works with slices. Here's another quick example, extending the previous one, to show that:

$ perl -E ' my $x = { a => 1, b => 2 }; say "@$x{qw{a b}}"; { local @$x{qw{a b}} = (3,4); say "@$x{qw{a b}}"; } say "@$x{qw{a b}}"; ' 1 2 3 4 1 2

And to show that the elements in the slice remain localised individually:

$ perl -E ' my $x = { a => 1, b => 2 }; say "@$x{qw{a b}}"; { local @$x{qw{a b}} = (3,4); say "@$x{qw{a b}}"; $x->{b} = "XYZ"; say "@$x{qw{a b}}"; } say "@$x{qw{a b}}"; ' 1 2 3 4 3 XYZ 1 2

Update (code reformatting): Upon revisiting this post about 10 hours after I originally wrote it, I observed that the first one-liner was possibly not as clear as I might have hoped, and the subsequent extensions to it resulted in that failing clarity heading in the direction of opacity. I've split each one-liner into multiple lines and added indentation to improve readability: none of the actual code has changed. Accordingly, I've also removed the "Apologies in advance for the wrapping" clause.

— Ken