# the first argument of this function is a filename
# the second argument is a reference to a hash of variables
# all variables in that hash will be written out to a file
# the format of the file is as follows
# SCALARS: s:name:value
# ARRAYS : a:name:value1:value2:value3
# HASHES : h:name:key1:value1:key2:value2
# newlines are the seperators! there is no terminating character
sub write_vars {
my $filename = shift @_;
my $vars = shift @_;
open(FILE, ">$filename");
foreach my $key (keys %{$vars}) {
# this one is just for convienence
my $i = \( $vars->{$key} );
# this is a switch statement
# make a reference to $vars->{$key} and pass it to ref
for (ref $i) {
# if it is scalar, ref will return SCALAR...
if (/SCALAR/) {
print FILE "s:$key:" . $vars->{$key} . ",\n";
}
# ...otherwise it returns an empty string
# which means it is a hash or an array
else {
$j = $vars->{$key};
$type = ref $j;
# if it is an array, print out each element
if ($type eq "ARRAY") {
print FILE "a:$key";
for my $element ( @{$j} ) {
print FILE ":$element";
}
}
# likewise for a hash, print out the key/value pairs
elsif ($type eq "HASH") {
print FILE "h:$key";
for my $k ( keys %{$j} ) {
print FILE ":$k:" . $j->{$k};
}
}
}
}
}
close(FILE);
return;
}
# the first argument of this function is a filename
# function returns a hash
# see the above function for the format of the file
sub read_vars {
my $filename = shift @_;
my %vars;
# these are used when extracting data from the fields
my ($type, $name, $value, $key);
open(FILE, $filename);
my @data = <FILE>;
close(FILE);
# iterate through the array
foreach my $line (@data) {
# retrieve the type
$type = substr($line, 0, 1);
for ($type) {
# if it's a scalar...
if (/s/) {
(undef,$name,$value) = split(/:/, $line, 3);
chomp $value;
$vars{$name} = $value;
}
# if it's an array...
if (/a/) {
# stores the elements of the array, temporarily
my ($values, @elements);
(undef,$name,$values) = split(/:/, $line, 3);
chomp $values;
@elements = split(/:/, $values);
# now we've got the values split up
# time to write things to the hash
$vars{$name} = (\@elements);
}
# if it's a hash...
if (/h/) {
# $k and $v are for key and value
my ($k, $v, $pairs, %hash);
(undef,$name,$pairs) = split(/:/, $line, 3);
chomp $pairs;
# extract all the pairs and put them in the hash
while ($pairs ne "") {
($k,$v,$pairs) = split(/:/, $pairs, 3);
$hash{$k} = $v;
}
# now shove a hash ref into our big hash!
$vars{$name} = (\%hash);
}
}
}
return %vars;
}