Thread

Posted on Wed Dec 28 21:34:43 2005 by earl
How do you suggest creating derived fields?

Suppose I am creating a class with a birthyear and age field. I use the birthyear field to calculate the value of the age field. Here is my initial arguments.

my %init_args :InitArgs = ('birthyear' => { 'Field' => \@birthyear_of } );

Since the age field initialization is non-trivial, I have to initialize age field within an":init" subroutine. Within the ":init" subroutine, I was having trouble finding the value of the birthyear. Object::InsideOut has removed the value of the birthyear from the hash. (IMHO, this is because that value was already used to initialize birth field). And I may not get it from the field, because it doesn't look like all the initialized fields are set before Perl calls the ":init" subroutine.

I'm thinking that I can remove the 'Field' attribute from %init_args, and do the birthyear initialization manually. However, if all the implicitly initialized fields were set before calling the :init subroutine, I could still do birthyear automatically.
Direct Responses: 1528 | Write a response
Posted on Wed Dec 28 23:20:56 2005 by jdhedden in response to 1527
Re: How do you suggest creating derived fields?
    And I may not get it from the field, because it doesn't look like all the
    initialized fields are set before Perl calls the ":init" subroutine.

No, the initialized fields are indeed set before the :Init subroutine is called. The following illustrates what I think you described:
#!/usr/bin/perl use strict; use warnings; package My::Class; { use Object::InsideOut; my @birthyear_of :Field('Get' => 'year'); my @age_of :Field('Get' => 'age'); my %init_args :InitArgs = ( 'birthyear' => { 'Field' => \@birthyear_of, 'Mandatory' => 1, }, ); sub init :Init { my ($self, $args) = @_; my $year = $birthyear_of[$$self]; my $age = (1900 + (localtime())[5]) - $year; $age_of[$$self] = $age; } } package main; MAIN: { my $obj = My::Class->new('birthyear' => 1957); print('Year: ', $obj->year(), "\n"); print('Age: ', $obj->age(), "\n"); } exit(0); # EOF
This produces the following output:
Year: 1957 Age: 48
Write a response