in reply to Setting accessor with Object::Tiny

I generally just use the Perl core object system rather than pulling in other packages. For what Object::Tiny gives you, have you considered using the core fields pragma instead?

I have often used an internal _set method like: (disclaimer: this exact code not tested)

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

Replies are listed 'Best First'.
Re^2: Setting accessor with Object::Tiny
by AnomalousMonk (Archbishop) on Aug 12, 2019 at 05:03 UTC
    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:  <%-{-{-{-<

      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:  <%-{-{-{-<