perlstorable

Can Storable store to the DATA filehandle?


I was curious if using Storable's store_fd and fd_retrieve would allow me to store a data structure into a program's own DATA filehandle. I realize this isn't Best Practice, I'm just curious if it'd work, my quick attempts to try it don't seem to work.


Solution

  • I'm not sure why you'd want to do that, but you can fake it. You should try to avoid that though.

    Just for giggles, you could open a filehandle, read lines from $0 and print them until you get to __DATA__, then add your new __DATA__ section. The trick is then to rename your new file to become $0, perhaps by an exec if your system locks the file while the program is running:

    #!perl
    
    my $mode = (stat($0))[2] & 07777;
    
    open my($fh), '<', $0 or die "I can't open me! $!\n";
    open my($new), '>', "$0.new" or die "I can't open you! $!\n";
    eval { chmod( $mode, $new ) } or warn "Couldn't set permissions: $@\n";
    
    while( <$fh> )
        {
        last if /^__DATA__$/;
        print { $new } $_;
        }
    
    print "I am $$\n";
    print { $new } "__DATA__\n", join '|', $$, time, (stat($0))[1];
    
    rename( "$0.new", $0 )
    
    __DATA__
    64574|1265415126|8843292