http://qs321.pair.com?node_id=192629

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow monks! I am using the below code in a script and cannot figure out how to automatically run the sub save_config before the script exits (to save any changes in the config hash to the config file). Any help is appreciated.

Code from main cgi file (foo.cgi):

#!/usr/bin/perl use strict; eval { require Foobar; my $self = Foobar->new; $SIG{__WARN__} = sub { die @_ }; $self->run; }; if ($@) { print "content-type: text/html\n\nError: $@"; exit; }
Code from Foobar.pm:
package Foobar; use strict; sub new { my $self = bless {}, shift; $self->init; } sub init { my $self = shift; $self->{build} = 1; $self->{version} = '1.0 alpha'; require CGI; $CGI::HEADERS_ONCE = 1; $self->{cgi} = CGI->new; require fbconfig; $self->{cfg} = fbconfig->get; # this is where I load the config fr +om fbconfig.pm (saved by the sub save_config) return $self; } sub run { # A page handler would go here } sub save_config { my $self = shift; use Data::Dumper; $Data::Dumper::Terse = 1; open XCFG, '>fbconfig.pm'; print XCFG "package fbconfig;\n\n"; print XCFG "sub get {\n return ", Dumper($self->{cfg}), ";\n\n} +\n\n1;"; close XCFG; } 1;
Sample fbconfig.pm:
package fbconfig; sub get { return { 'key' => 'value' } ; } 1;

Replies are listed 'Best First'.
Re: Running a sub before a script exits?
by rattusillegitimus (Friar) on Aug 25, 2002 at 04:13 UTC

    Would calling the save_config from a destructor on the object work for you? Something like the following added to package FooBar:

    #untested sub DESTROY { my $self = shift; $self->save_config; }

    -rattus
    __________
    He seemed like such a nice guy to his neighbors / Kept to himself and never bothered them with favors
    - Jefferson Airplane, "Assassin"

      Thank you SOOOOO much, that works great! I didn't even know about DESTROY :)

        No problem. ;) I highly recommend all the various OO pods as well as theDamian's Object Oriented Perl. (I consulted the latter about DESTROY right before posting)

Re: Running a sub before a script exits?
by dws (Chancellor) on Aug 25, 2002 at 04:09 UTC
    I am using the below code in a script and cannot figure out how to automatically run the sub save_config before the script exits.

    END { save_config() }

    Ignore that. rattusillegitimus has a better answer below.

      Not necessarily.

      In most versions of Perl if your variable is pointed at by a global, it is DESTROYed haphazardly in global destruction. Therefore you may not have a config left to save when DESTROY is called. But you always should in END.