Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: inside-out objects using arrays?

by borisz (Canon)
on Sep 17, 2005 at 23:13 UTC ( [id://492934]=note: print w/replies, xml ) Need Help??


in reply to inside-out objects using arrays?

Better use a hash, since you may delete objects. Take a look at Class::Std for some hints, if you really want these objects.
Boris

Replies are listed 'Best First'.
Re^2: inside-out objects using arrays?
by rvosa (Curate) on Sep 17, 2005 at 23:34 UTC
    I was thinking the following, which would lead to undef array elements once $obj->DESTROY gets called. Still, I like it ;-)
    package Outside::In; use strict; use warnings; { my $obj_counter = 0; my @name; sub new { my $class = shift; my $instance_index = $obj_counter; my $self = sub { return $instance_index }; bless $self, $class; $obj_counter++; return $self; } sub name { my $self = shift; $name[$self->()] = shift if @_; return $name[$self->()]; } sub DESTROY { my $self = shift; delete $name[$self->()]; } } package main; my $obj1 = Outside::In->new; my $obj2 = Outside::In->new; $obj1->name('Bob'); $obj2->name('Fred'); print $obj1->name, "\n", $obj2->name, "\n"; print $obj1->();
      I was thinking the following, which would lead to undef array elements once $obj->DESTROY gets called. Still, I like it ;-)

      The point borisz was making is that with a solution like this  @name always increases in length as objects are created and deleted, which will lead to you running out of memory in the long term.

        You could avoid that problem by assigning the index to the first undef slot, rather than straight incrementing:

        my $instance_index = List::Util::first { !defined $_ } @name;

        You end up, though, with an O(n) constructor. But perhaps the savings in access make up for this.

        I know, I was sort of making that point also. Then I started thinking about how to regain the empty slots, but as fishbot_v2 mentions, that's O(N). Conceivably, you might want to take that performance hit of you subsequently do lots (and lots and lots and lots) of lookups...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://492934]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-24 01:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found