summaryrefslogtreecommitdiff
path: root/lib/Simplestore.pm
blob: aea8b2b3e87764c45e121ca85abea643ae7ff55e (plain)
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
#!/usr/bin/env perl
## Library for the Simplestore format
## Copyright © 2009 by Daniel Friesel <derf@derf.homelinux.org>
## License: WTFPL <http://sam.zoy.org/wtfpl>
use strict;
use warnings;

our (@ISA, @EXPORT, $VERSION);
require Exporter;
@ISA = ('Exporter');
@EXPORT = ('load', 'save');
$VERSION = '1.0';

sub load {
	my $file = shift;
	my ($store, $key, $value);
	$store = shift if @_;
	open(my $handle, '<', $file) or die("Cannot read $file: $!");
	while (<$handle>) {
		chomp;
		/^(\S+)\s+(.*)$/ or next;
		($key, $value) = ($1, $2);
		if (exists($store->{$key})) {
			$store->{$key} .= "\n$value";
		} else {
			$store->{$key} = $value;
		}
	}
	close($handle);
	return($store);
}

sub save {
	my ($file, $store) = @_;
	my $key;
	open(my $handle, '>', $file) or die("Cannot open $file: $!");
	foreach $key (keys(%$store)) {
		foreach (split(/\n/, $store->{$key})) {
			print $handle "$key\t$_\n";
		}
	}
	close($handle);
}

1;