in reply to Re^5: how to let sub return hash of 2 sub?
in thread how to let sub return hash of 2 sub?

However, that class doesn't have to have a 'new' method; and I'd argue that it's really superfluous, if the class's use cases are no more complex than this.

return bless { name => $name, val => $val }, 'NameValTuple';

The one potential downside of this is that it "exposes" the representation of the underlying object (in this case, a hash). Having a 'new' method hides all that. I personally believe that, at least in a simple case like this, there's hardly anything to be gained from hiding it.

Replies are listed 'Best First'.
Re^7: how to let sub return hash of 2 sub?
by ikegami (Patriarch) on May 29, 2015 at 16:14 UTC
    You could inline new, but you still need name and val.

    I don't see the point of changing

    return NameValTuple->new( name => $name, val => $val ); { package NameValTuple; sub new { my $class = shift; bless({ @_ }, $class) } sub name { $_[0]->{name} } sub val { $_[0]->{val} } }
    to
    return bless { name => $name, val => $val }, 'NameValTuple'; { package NameValTuple; sub name { $_[0]->{name} } sub val { $_[0]->{val} } }

    It breaks encapsulation for no reason.