Search code examples
perlmoose

Perl::Moose: Using a read accessor to return only a calculated value


Thank you for your help!

Lets say I have a class Stock:

package Stock;
use Moose;

has 'quantity' => ( is => 'rw', );
has 'price'    => ( is => 'rw', );
has 'value'    => ( is => 'ro', );

1;

How can I calculate the value (quantity*price) when value is used, not when price or quantity change?

EDIT: Sorry, if this was not complete, but of course value should always return the latest value of quantity*price, as those can change.

This should be simple, but I guess I don't see the wood for the all trees...

Thank you very much for your help!


Solution

  • You probably want a normal method:

    package Stock;
    use Moose;
    
    has 'quantity' => ( is => 'rw', );
    has 'price'    => ( is => 'rw', );
    
    sub value {
      my $self = shift;
      return $self->quantity * $self->price;
    }
    

    Alternatively, hook into the setters for quantity and price and have them update the value whenever a new value is set.

    Advantage of hooks: The value is cached, which is good when the calculation is expensive (not the case here).
    Advantage of a simple method: Easier to implement.