Writing a persistent perl script

前端 未结 4 473
無奈伤痛
無奈伤痛 2020-12-09 23:59

I am trying to write a persistent/cached script. The code would look something like this:

...
Memoize(\'process_fille\');
print process_file($ARGV[0]);
...
s         


        
4条回答
  •  误落风尘
    2020-12-10 00:24

    This is kind of dark magic, but you can store state after your script's __DATA__ token and persist it.

    use Data::Dumper; # or JSON, YAML, or any other data serializer
    package MyPackage;
    my $DATA_ptr;
    our $state;
    INIT {
        $DATA_ptr = tell DATA;
        $state = eval join "", ;
    }
    
    ...
    manipulate $MyPackage::state in this and other scripts
    ...
    
    END {
        open DATA, '+<', $0;   # $0 is the name of this script
        seek DATA, $DATA_ptr, 0;
        print DATA Data::Dumper::Dumper($state);
        truncate DATA, tell DATA;  # in case new data is shorter than old data
        close DATA;
    }
    __DATA__
    $VAR1 = {
        'foo' => 123,
        'bar' => 42,
        ...
    }
    

    In the INIT block, store the position of the beginning of your file's __DATA__ section and deserialize your state. In the END block, you reserialize the current state and overwrite the __DATA__ section of your script. Of course, the user running the script needs to have write permission on the script.

    Edited to use INIT block instead of BEGIN block -- the DATA block is not set up during the compile phase.

提交回复
热议问题