in reply to Hash assignment: Undocumented feature?

... a method of changing several values at once.

I don't see this as a valid way of looking at this behavior. A hash key is always unique, and a hash key always has exactly one scalar value, although this scalar may be a reference to... well, anything, opening up vast possibilities for data structures, code dispatch tables, etc., etc., etc. So the only way to "[change] several values at once" is to replace a (scalar) reference to a bunch of stuff with another (scalar) reference to a different bunch of stuff.

Maybe one useful approximation to "changing several values at once", but with "changing" better understood as "dealing with", is the Perl idiom for implementing named, defaulted, non-positional function arguments. It goes something like:

>perl -wMstrict -le "sub D { my %defaults = qw(foo 999 bar 888 baz 777); ;; my ($hr_args) = @_; my %arguments = (%defaults, %{ $hr_args || {} }); ;; print qq{foo $arguments{foo} bar $arguments{bar} baz $arguments{b +az}}; } ;; D(); ;; D({bar => 2}); ;; D({baz => 1, foo => 3}); " foo 999 bar 888 baz 777 foo 999 bar 2 baz 777 foo 3 bar 888 baz 1

Replies are listed 'Best First'.
Re^2: Hash assignment: UndERDocumented feature?
by fsavigny (Novice) on Aug 11, 2013 at 17:18 UTC

    (Oops. Didn't really need to dash off, on second thought.) I slightly suspect your example is more complex than I can deal with. What I meant is simply something like this (and I think it does not matter if the values are simple scalars or references to something complex):

    %what_all_workers_have = ( holidays => 30, hours_per_week => 40, office_space => 10, job_title => "Clerk", ); ## turning to John, who is a wheelchair user: %what_john_has = ( %what_all_workers_have, office_space => 20, # needs room to maneuvre hours_per_week => 35, # needs more breaks );

    One needn't even worry if %workers_have actually contains the keys office_space and hours_per_week. It will either add or overwrite them, whichever is required. To me, this seems quite elegant and time-saving. In any case, it's less code to type than any other version I could think of.

      %what_john_has = ( %what_all_workers_have, office_space => 20, # needs room to maneuvre hours_per_week => 35, # needs more breaks );

      That's kinda like what
          my %arguments = (%$hr_defaults, %{ $hr_args || {} });
      is doing in my example code: as you've written,  %what_all_workers_have is the default of what a particular worker has.