in reply to Problems I've had with array based objects
It trades space (possibly a lot of space) for time and convenience, but that's often a good trade. I'm sure there's a (perhaps non-trivial) way to move the index references back into package space to save memory, but I'll leave that as an exercise.package foo; use strict; sub new { bless [], ref $_[0] || $_[0] || __PACKAGE__; } sub declare { my $self = shift; ## auto vivification fails to make the correct indexes $self->[0] = {} unless $self->[0]; no strict 'refs'; foreach my $name (@_) { ## create the index reference $self->[0]{$name} = @$self; ## create a nicely named index variable ${ref($self) . '::' . $name . '_idx'} = @$self; ## create the accessor/mutator methods (my $code = 'sub { $_[0][VALUE] }') =~ s/VALUE/scalar @$self/e +; *{ref($self) . '::get_' . $name} = eval $code; ($code = 'sub { $_[0][VALUE] = $_[1] }') =~ s/VALUE/scalar @$s +elf/e; *{ref($self) . '::set_' . $name} = eval $code; ## create the (unitialized) attribute itself push @$self, undef; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Problems I've had with array based objects
by ikegami (Patriarch) on Aug 04, 2006 at 00:39 UTC | |
by vanishing (Initiate) on Aug 05, 2006 at 03:39 UTC |