how to run piece of code just before the exit of perl script

前端 未结 3 1791
旧巷少年郎
旧巷少年郎 2021-01-02 03:20

In my script, I need to load some info from disk file and during the run of script the info might be changed.To keep the consistence of the file in disk and it\'s in memory

3条回答
  •  隐瞒了意图╮
    2021-01-02 04:02

    There's two different ways to do this, depending on what you're looking for.

    • The END block is executed when the interpreter is shut down. See the previous answer for more details :)
    • The DESTROY block/sub, that is executed when your object goes out of scope. That is, if you want to embed your logic into a module or class, then you can use DESTROY.

    Take a look at the following example (it's a working example, but some details like error checking, etc.. are omitted):

    #!/usr/bin/env perl
    
    package File::Persistent;
    
    use strict;
    use warnings;
    use File::Slurp;
    
    sub new {
        my ($class, $opt) = @_;
    
        $opt ||= {};
    
        my $filename = $opt->{filename} || "./tmpfile";
        my $self = {
            _filename => $filename,
            _content => "",
        };
    
        # Read in existing content
        if (-s $filename) {
            $self->{_content} = File::Slurp::read_file($filename);
        }
    
        bless $self, $class;
    }
    
    sub filename {
        my ($self) = @_;
        return $self->{_filename};
    }
    
    sub write {
        my ($self, @lines) = @_;
        $self->{_content} .= join("\n", @lines);
        return;
    }
    
    sub DESTROY {
        my ($self) = @_;
        open my $file_handle, '>', $self->filename
            or die "Couldn't save persistent storage: $!";
        print $file_handle $self->{_content};
        close $file_handle;
    }
    
    # Your script starts here...
    package main;
    
    my $file = File::Persistent->new();
    
    $file->write("Some content\n");
    
    # Time passes...
    $file->write("Something else\n");
    
    # Time passes...
    $file->write("I should be done now\n");
    
    # File will be written to only here..
    

提交回复
热议问题