Question

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!

Was it helpful?

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.

OTHER TIPS

package Stock;
use Moose;

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

before 'value' => sub { $_[0]->set_value($_[0]->price * $_[0]->quantity) };

1;

package main;

$\ = $/;
my $b = Stock->new(price=>100, quantity=>99);

print $b->value;

$b->price(10);
$b->quantity(87);

print $b->value;

This will print:

9900
870
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top