[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]

pseudohash module



not sure how pseudohashes are implemented in perl.
the attached module creates a pseudohash class
that behaves consistent with a real hash.

it does slow down some methods/functions that
have to filter out deleted keys.
dont know if it gains anything, but it does
appear to behave like a real hash then.

Greg
use strict;

#######################
package pseudohash;

sub new
{
	my $class=shift;
	my %keys;
	my $self = [ \%keys ];
	bless($self,$class);
	return $self;
}



########################################################
# send in a bunch of key/value pairs and store them away.
########################################################
sub assign
{
 my $obj=shift;
 my $key_r = $obj->[0];
 while(@_)
  {
  my $key = shift;
  my $value = shift;
  my $index = $key_r->{$key};

  # if it doesn't exist, tack it on the end
  unless(defined($index))
   {
   $index = @$obj;
   push(@$obj, $value);
   $key_r->{$key} = $index;
   }
  else
   {
   $obj->[$index] = $value;
   }
  }
}


########################################################
# given a key, return its value
########################################################
sub getvalue
{
 my ($obj,$key) = @_;
 my $key_r = $obj->[0];

 my $index = $key_r->{$key};
 return undef unless(defined($index));
 return $obj->[$index];
}


########################################################
# delete a given key for the pseudohash
# implementation: set the key_r value to undef
# if value in key hash is set to undef, that key/value
# pair doesn't exist AND it preserves indexes in pseudohash.
########################################################
sub delete
{
 my ($obj,$key) = @_;
 my $key_r = $obj->[0];

 my $index = $key_r->{$key};
 if(defined($index))
  {
  $key_r->{$key} = undef;
  }

}


sub exists
{
 my ($obj,$key) = @_;
 my $key_r = $obj->[0];
 return $key_r->{$key};
}

sub keys
{
 my ($obj) = @_;
 my $key_r = $obj->[0];
 my @full_key_list = keys(%$key_r);

 # filter out the ones "deleted" from pseudohash
 my @filtered_key_list;
 foreach my $key (@full_key_list)
  {
  push (@filtered_key_list, $key) if ($obj->exists($key));
  } 
 return @filtered_key_list;
}



sub values
{
 my ($obj) = @_;
 my $key_r = $obj->[0];
 my @full_key_list = keys(%$key_r);

 # filter out the ones "deleted" from pseudohash
 my @value_list;
 foreach my $key (@full_key_list)
  {
  push(@value_list, $obj->[$key_r->{$key}]) if($obj->exists($key));
  } 
 return @value_list;
}

######################
# end of file return 1
1;
######################

Follow-Ups from:
Matt Sergeant <matt@sergeant.org>

[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]