in reply to Saving the state of a recursive program
#!/usr/bin/perl -w use strict; use constant RDELIM => "\x00"; use constant ADELIM => "\x01"; my @state; my @f_state; my $state_file = "saved.state"; $SIG{INT} = \&freeze; sub freeze { open (STATE, ">$state_file") || die "Could not save state to $state_file, sorry\n"; foreach (@state) { my ($args, $vars) = @$_; print "@$args...@$vars\n"; print STATE join(RDELIM, @$args); print STATE ADELIM; print STATE join(RDELIM, map { $$_ } @$vars); print STATE "\n"; } close (STATE); exit (0); } sub thaw { # If the file can't be opened, just restart open (STATE, $state_file) || return; @f_state = (); while (<STATE>) { chomp; push (@f_state, [ map { [ split(RDELIM, $_) ] } split(ADELIM, $_) ]); } close (STATE); } sub arg_push { push(@state, [shift(@_), [@_]]); } sub arg_pop { pop(@state); } sub arg_thaw { my ($args,$vars) = @{shift(@f_state)}; @{shift()} = @$args; foreach (@_) { $$_ = shift(@$vars); } } use constant DEPTH => 4; sub recurse { my ($x,$y,$X,$Y); my @args = @_; arg_push(\@args, \$x, \$y); # If there is frozen data specified to at least # this depth... if (@f_state) { # ...use that instead. arg_thaw(\@args, \$X, \$Y); print "Resuming @args ($X,$Y)\n"; } my ($what) = @args; $X = 0 unless (defined($X)); $Y = 'a' unless (defined($Y)); print "$what\n" if (@state == 3); if (length($what) <= DEPTH) { for my $x_iter ($X..'9') { for my $y_iter ($Y..'z') { $x = $x_iter; # Copy $y = $y_iter; recurse("$what$x_iter$y_iter"); } } } pop(@state); } thaw(); recurse('');
|
|---|