in reply to Re: Setting accessor with Object::Tiny
in thread Setting accessor with Object::Tiny

sub _set { my $self = shift; my ($key, $value); while (($key, $value) = splice @_, 0, 2) { $self->{$key} = $value +} }

For this, why not just:

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub _set { my $self = shift; %$self = (%$self, @_); } ;; my $hr = bless { qw(y 25 z 26) }; ;; $hr->_set(qw(a 1 b 2 c 3)); dd $hr; " bless({ a => 1, b => 2, c => 3, "y" => 25, z => 26 }, "main")


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^3: Setting accessor with Object::Tiny
by jcb (Parson) on Aug 12, 2019 at 05:10 UTC

    Because I had not thought of that? :-) It figures that there would be a more compact way to do that.

    Although if I had objects being mutated in an inner loop, I would want to compare both ways, in case changing a few keys is faster than setting the whole hash.

      while (($key, $value) = splice @_, 0, 2) { $self->{$key} = $value }

      Although I notice that the while-loop version allows assignment of an unpaired key/value (i.e., if the shift-ed  @_ array has an odd number of elements, the last element/key of the array has no value and is assigned as undef) without a warning. The list assignment version must be changed to something like
          %$self = (%$self, @_, @_ & 1 ? undef : ());
      to avoid a warning (if this is desireable), and this, I must admit, is a bit more messy.

      Update: But I guess a simple
          no warnings 'misc';
          %$self = (%$self, @_);
      would suppress that warning just as well.


      Give a man a fish:  <%-{-{-{-<

        In my code _set methods are always called with key => value pairs. Silently assigning undef is actually a bug, but (I said that code had not been tested) could be fixed by adding die "unbalanced assignment group: ".join(', ', @_) if @_ & 1; which is also a bit more messy.

        I personally believe that no warnings (along with no strict) should be syntax-highlighted in bright bold primary red and generally avoided. There are a few times I have had to write no strict, usually when doing some types of meta-programming, but it is very rare in my code. I am not sure if I have ever written no warnings.