12.5.6 A Subroutine That Returns Several Closures: Simulating a “Database"
12.5.6 A Subroutine That Returns Several Closures: Simulating a “Database"
In this section, we write a function that returns a set of references to closures that perform several tasks on a data structure. We can use this to simulate the functions of a simple "database".
Program 12.23
sub funcall{
my ($funRef, @argument) = @_;
&$funRef(@argument);
}
sub makeDBMS{
my %DB = @_;
my $accessDB = sub{
my $key = $_[0];
$DB{$key}
};
my $setDB = sub{
my ($key, $val) = @_;
$DB{$key} = $val;
};
my $deleteDB = sub{
my $key = $_[0];
delete $DB{$key};
$key
};
return ($accessDB, $setDB, $deleteDB);
}
Once we have defined the subprogram makeDBMS and the closures inside it, we can use the closures returned to work on a shared data structure. A shared data structure is built below.
@citiesDB = makeDBMS ('Boston' => 'US', 'Paris' => 'France',
'Nagaon' => 'Assam');
This call creates citiesDB as a data structure that provides with associated access, assignment and deletion functions. The data structure is hidden from outside and can be accessed only indirectly through calls to the three functions. The three functions are obtained as elements of the citiesDB array. So, now we can make calls such as the following.
funcall ($citiesDB[0], 'Boston')
funcall ($citiesDB[1], 'London' => 'UK')
funcall ($citiesDB[0], 'London')
The first call accesses the element of the database that has Boston as the key. The call returns US. The second call enters a new pair of elements in the database with London the key and UK the value. So, the third call returns UK, the value corresponding to the new key just entered.
It may be a little awkward to make calls such as the above where the function is an element of an array. To make things look a little nicer, we can define new functions such as lookup given below. lookup is the new access function for a database.
Program 12.24
sub lookup{
my ($key, @myDB) = @_;
funcall ($myDB[0], $key);
}
Once we have defined lookup, we can create new databases and access elements as given below.
%myBestFriends = ('Tommy' => 'Washington DC', 'Chad' => 'San Francisco',
'Jeff' => 'Boulder', 'Rick' => 'Montreal',
'Sean' => 'Montreal');
@myBestFriendsDB = makeDBMS (%myBestFriends);
printf "Tommy: %s\n", lookup ('Tommy', @myBestFriendsDB);
printf "Rick: %s\n", lookup ('Rick', @myBestFriendsDB);
printf "Jeff: %s\n", lookup ('Jeff', @myBestFriendsDB);
