How this works is for each instance variable desired in the parameters passed to the "InstanceVariables" module, a tied variable with the appropriate name is created for the package. These variables are tied to sub routines that access the package variable "$self". So for each method the first argument is shifted in a 'local $self'. Then when the tied variables are accessed the appropriate object is altered or accessed.use strict; package person; use Class::InstanceVariables qw( $first $last $middle ); sub new{ my $class = shift; local $self = instance(); $first = shift; $middle = shift; $last = shift; return $self; } sub full_name{ local $self = shift; return "$last, $first $middle"; } sub marry{ local $self = shift; my $spouse = shift; return "$first married ".$spouse->first(); } package main; my $john = new person(qw(John F Jones)); my $sue = new person(qw(Suzy P Edwards)); print $john->full_name()."\n"; print $sue->full_name()."\n"; print $john->marry($sue)."\n";
use strict; package Class::InstanceVariables; sub import{ my $class = shift; my $caller = caller(); my $ties = "package $caller;\n".'no strict; $self=""; sub TIESCALAR{ my $class = shift; my $var = shift; bless \$var,$class; } sub FETCH{ my $thing = shift; $self->{$$thing}; } sub STORE{ my $thing = shift; $self->{$$thing} = shift; } '; no strict 'refs'; *{$caller."::self"} = \${$caller."::self"}; foreach my $ivar (@_) { if($ivar!~/^\$([A-Za-z_]\w*)$/) { die "$ivar is not a valid variable name!\n"; } my $varname = $1; *{$caller."\:\:$varname"} = \${$caller."\:\:$varname"}; $ties .= "sub $varname : lvalue { \$_[0]->{$varname} }\n"; $ties .= "tie \${$varname},'$caller','$varname';\n"; } *{$caller."::instance"}=sub{ bless {},$caller; }; eval $ties; if ($@) { die $@; } } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Overhead vs. ease of use in OOP
by jeffa (Bishop) on Oct 17, 2003 at 19:12 UTC | |
|
Re: Overhead vs. ease of use in OOP
by demerphq (Chancellor) on Oct 17, 2003 at 19:07 UTC | |
by Abigail-II (Bishop) on Oct 19, 2003 at 13:12 UTC | |
by demerphq (Chancellor) on Oct 19, 2003 at 23:14 UTC | |
|
Re: Overhead vs. ease of use in OOP
by Anonymous Monk on Oct 17, 2003 at 16:33 UTC | |
|
Re: Overhead vs. ease of use in OOP
by simonm (Vicar) on Oct 17, 2003 at 20:10 UTC | |
|
Re: Overhead vs. ease of use in OOP
by BrowserUk (Patriarch) on Oct 18, 2003 at 01:18 UTC | |
by fletcher_the_dog (Friar) on Oct 20, 2003 at 14:09 UTC | |
|
Re: Overhead vs. ease of use in OOP
by fletcher_the_dog (Friar) on Oct 17, 2003 at 20:51 UTC | |
by chromatic (Archbishop) on Oct 18, 2003 at 00:25 UTC |