1 |
package Cache::CacheUtilities;
|
2 |
require 5.004;
|
3 |
use Data::Dumper;
|
4 |
BEGIN {
|
5 |
$Cache::CacheUtilities::zipUntility="GZip";
|
6 |
$Data::Dumper::Varname='cache';
|
7 |
}
|
8 |
|
9 |
sub read()
|
10 |
{
|
11 |
my ($file) = @_;
|
12 |
my $data=();
|
13 |
my $func="read${zipUntility}";
|
14 |
&$func($file,\$data);
|
15 |
my $cache = eval "$data";
|
16 |
die "Cache $file load error: ",$@,"\n", if ($@);
|
17 |
return $cache;
|
18 |
}
|
19 |
|
20 |
sub write()
|
21 |
{
|
22 |
my ($cache,$file)=@_;
|
23 |
use File::Copy;
|
24 |
if (-r $file){move($file,"${file}.bak");}
|
25 |
my $ok=1; my $err="";
|
26 |
my $fcache=();
|
27 |
eval {$fcache=Dumper($cache);};
|
28 |
if ($@){$err=$@;$ok=0;}
|
29 |
else
|
30 |
{
|
31 |
my $func="write${zipUntility}";
|
32 |
$ok = &$func($fcache,$file);
|
33 |
}
|
34 |
if ($ok)
|
35 |
{
|
36 |
unlink ("${file}.bak");
|
37 |
my $mode=0644;
|
38 |
chmod $mode,$file;
|
39 |
}
|
40 |
else
|
41 |
{
|
42 |
if (-r "${file}.bak"){move("${file}.bak",$file);}
|
43 |
die "ERROR: Writing Cache file $file: $err\n";
|
44 |
}
|
45 |
return;
|
46 |
}
|
47 |
|
48 |
###### Using gzip #################
|
49 |
sub readGZip()
|
50 |
{
|
51 |
my $file = shift;
|
52 |
my $data = shift;
|
53 |
my $gz;
|
54 |
if (open($gz,"gzip -cd $file |"))
|
55 |
{
|
56 |
binmode $gz;
|
57 |
my $buf;
|
58 |
while (read($gz,$buf,1024*1024) > 0){${$data}.=$buf;}
|
59 |
close($gz);
|
60 |
}
|
61 |
else{die "Can not open file for reading using \"gzip\": $file\n";}
|
62 |
return;
|
63 |
}
|
64 |
|
65 |
sub writeGZip()
|
66 |
{
|
67 |
my ($cache,$file) = @_;
|
68 |
my $gz;
|
69 |
if (open($gz,"| gzip >$file"))
|
70 |
{
|
71 |
binmode $gz;
|
72 |
print $gz $cache;
|
73 |
close($gz);
|
74 |
}
|
75 |
else{die "Can not open file for reading using \"gzip\": $file\n";}
|
76 |
return 1;
|
77 |
}
|
78 |
|
79 |
1;
|