1 |
#
|
2 |
# HashDB.pm
|
3 |
#
|
4 |
# Originally Written by Christopher Williams
|
5 |
#
|
6 |
# Description
|
7 |
#
|
8 |
# Interface
|
9 |
# ---------
|
10 |
# new() : A new HashDB object
|
11 |
# setdata(data, @keys) : set a data item to the given keys
|
12 |
# getdata(@keys) : return all data items that match the given keys
|
13 |
# deletedata(@keys) : detete all data items that match the given keys
|
14 |
# items() : return the number of seperate items in the store
|
15 |
|
16 |
package Utilities::HashDB;
|
17 |
require 5.001;
|
18 |
|
19 |
sub new {
|
20 |
my $class=shift;
|
21 |
$self={};
|
22 |
bless $self, $class;
|
23 |
$self->{datahash}=();
|
24 |
$self->{datakey}=();
|
25 |
return $self;
|
26 |
}
|
27 |
|
28 |
sub setdata {
|
29 |
my $self=shift;
|
30 |
my $data=shift;
|
31 |
my @keys=@_;
|
32 |
|
33 |
push @{$self->{datakey}}, [ @keys ];
|
34 |
push @{$self->{datahash}}, $data;
|
35 |
}
|
36 |
|
37 |
sub items {
|
38 |
my $self=shift;
|
39 |
return $#{$self->{datahash}};
|
40 |
}
|
41 |
|
42 |
|
43 |
sub getdata {
|
44 |
my $self=shift;
|
45 |
my @keys=@_;
|
46 |
|
47 |
my @data=();
|
48 |
my @match=$self->_match(@keys);
|
49 |
foreach $d ( @match ) {
|
50 |
push @data, $self->{datahash}[$d];
|
51 |
}
|
52 |
return @data;
|
53 |
}
|
54 |
|
55 |
sub deletedata {
|
56 |
my $self=shift;
|
57 |
my @keys=@_;
|
58 |
|
59 |
# first get all the keys we want to delete
|
60 |
my @match=$self->_match(@keys);
|
61 |
foreach $i ( @match ) {
|
62 |
print $i;
|
63 |
splice ( @{$self->{datahash}}, $i, 1 );
|
64 |
splice ( @{$self->{datakey}}, $i, 1 );
|
65 |
}
|
66 |
}
|
67 |
|
68 |
# ------------------- Support Routines ------------
|
69 |
# returns list of array indices of items matching the keys
|
70 |
sub _match {
|
71 |
my $self=shift;
|
72 |
my @keys=@_;
|
73 |
|
74 |
my $i;
|
75 |
my @matchold;
|
76 |
my @matchnew;
|
77 |
# At the start everything matches
|
78 |
for ( $i=0; $i<=$self->items(); $i++ ) {
|
79 |
if ( $#{$self->{datakey}[$i]} >= $#keys ) {
|
80 |
push @matchold, $i;
|
81 |
}
|
82 |
}
|
83 |
|
84 |
# now test against keys
|
85 |
for ( $i=0; $i <= $#keys; $i++ ) {
|
86 |
undef @matchnew;
|
87 |
foreach $dn ( @matchold ){
|
88 |
if ( $self->{datakey}[$dn][$i] eq $keys[$i] ) {
|
89 |
push @matchnew,$dn;
|
90 |
#print "match at $dn $keys[$i]\n";
|
91 |
}
|
92 |
}
|
93 |
@matchold=@matchnew;
|
94 |
}
|
95 |
return @matchold; # list of array indecies
|
96 |
}
|
97 |
|