[boulder.pm] Persistant Data

Eric Shore Baur baur at frii.com
Mon Jul 17 22:27:13 CDT 2000


    This is pretty much just an example out of the Perl Cookbook (p.506) about
keeping variables around between instances of a program... but it doesn't seem
to work even when I copied it straight out of the book.  ???
    This is a slightly modified version of it... basically, it prints that the
variables aren't defined every time I run it.

#!/usr/bin/perl
use MLDBM qw(DB_File);

my ($v1, $v2);

my $store = '/tmp/data';

BEGIN {
    print "BEGIN:\n";
    my %data;
    tie(%data, 'MLDBM', $store) or die "Can't tie to $store : $!\n";
    $v1 = $data{v1};
    $v2 = $data{v2};
    untie %data;
}

if (not defined $v1) {
    print "Variables not defined yet...\n";
    $v1 = 0;
    $v2 = 0;
}
print "\$v1 = $v1\n\$v2 = $v2\n";
$v1++;
$v2--;

END {
    print "END:\n";
    my %data;
    tie(%data, 'MLDBM', $store) or die "Can't tie to $store : $!\n";
    $data{v1} = $v1;
    $data{v2} = $v2;
    untie %data;
}

__END__

    If I take out the "BEGIN" and "END" and just have those code blocks in the
main body of the script, it works perfectly, but it doesn't seem to work with
that code in those special blocks.  It seems that it might have something to do
with the variables going out of scope, but the authors seem to think it'll work. 
(Right now I'm working with perl 5.6, but I seem to remember having this problem
with 5.005 (or was it 5.004?) as well.
    The program I'm running this in would work a lot better with the BEGIN and
END blocks... although I suppose I could do with just the END if I had to (I'm
writing a small "server" that needs to be able to save it's data if it dies for
some reason, but will otherwise always be running.)  Mainly, I'm curious now. 
:)

Thanks!
Eric





More information about the Boulder-pm mailing list