File: DictFile.pm

package info (click to toggle)
munin 2.0.76-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,064 kB
  • sloc: perl: 11,684; java: 1,924; sh: 1,632; makefile: 636; javascript: 365; python: 267
file content (67 lines) | stat: -rw-r--r-- 1,432 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package Munin::Common::DictFile;
require Tie::Hash;
our @ISA = qw(Tie::StdHash);

our $DEBUG_ENABLED;

# The method invoked by the command tie %hash, classname. 
# Associates a new hash instance with the specified class. 
# LIST would represent additional arguments (along the lines 
# of AnyDBM_File and compatriots) needed to complete the association.
sub TIEHASH {
	my $classname = shift;

	my ($filename) = @_;

	my $self = {
		__filename__ => $filename,
	};

	# Read the whole file if it exists
	if (-e $filename) {
		open(FILE, $filename) or die "Cannot open tied file '$filename' - $!";

		while(my $line = <FILE>) {
			chomp($line);
			next unless $line =~ m/^'(.*)':\t'(.*)'$/;
			# Found a valid line, store it
			$self->{ _unescape($1) } = _unescape($2);
		}
		close(FILE);
	}

	return bless($self, $classname);
}

# Write everything down
sub DESTROY {
	my $self = shift;
	
	my $tmp_filename = $self->{__filename__} . ".tmp.$$";

	open(FILE, "> $tmp_filename") or die "Cannot open temp file '$tmp_filename' - $!";
	foreach my $key (keys %$self) {
		print FILE "'" . _escape($key) . "':\t'" . _escape($self->{$key}) . "'\n"; 
	}
	close (FILE);

	rename $tmp_filename, $self->{__filename__};
}

sub DEBUG {
	print STDOUT "[DEBUG] @_" . "\n" if $DEBUG_ENABLED; 
}

sub _escape {
	my $string = shift;
	$string =~ s/'/''/g;
	return $string;
}

sub _unescape {
	my $string = shift;
	$string =~ s/''/'/g;
	return $string;
}

1;