如何在perl脚本退出之前运行一段代码 [英] how to run piece of code just before the exit of perl script

查看:66
本文介绍了如何在perl脚本退出之前运行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的脚本中,我需要从磁盘文件加载一些信息,并且在脚本运行期间,信息可能会更改.为了保持文件在磁盘中的一致性,我需要在内存中复制每当信息在内存中更改或定期写入时将信息写回磁盘回磁盘或在脚本退出时直接写回,这是首选方法,因为这样可以节省大量 IO 时间并使脚本具有响应性.

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 copy I need to write back the info to disk whenever the info is changed in memory or periodically write them back to disk or just write them back at the time of the script exit, which is the preferred one, because it will save lots of IO time and make the script responsive.

就像标题一样,我的问题是 perl 是否有一些机制可以满足我的需求?

So just as the title, my question is does perl has some mechanism that will meet my needs?

推荐答案

有两种不同的方法可以做到这一点,具体取决于您要查找的内容.

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

  • END 块在解释器关闭时执行.有关更多详细信息,请参阅上一个答案:)
  • DESTROY 块/子,当您的对象超出范围时执行.也就是说,如果您想将您的逻辑嵌入到模块或类中,那么您可以使用 DESTROY.
  • 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..

这篇关于如何在perl脚本退出之前运行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆