I use Storable (using its lock_xxx methods) to maintain data between a couple of processes, but in one instance I want to amend the data in the stored file.

So, I open the file to get a filehandle, lock it, then use the store_fd and retrieve_fd on the filehandle (to prevent possible race conditions between using lock_store and lock_retrieve from the other processes), but have discovered it doesn't work a I expected. Is this a problem with Storable or my understanding?

Update: Fixed thanks to zwon - was missing a truncate and seek before rewriting the file

#!/usr/bin/perl use strict; use warnings; use Storable qw(retrieve store retrieve_fd store_fd); use Fcntl qw(:flock); my $file='/tmp/storable_test'; my %data = ( item => 'Here I am', ); store(\%data, $file); #===== # open & lock file open(my $fh, '+<', $file); flock($fh, LOCK_EX); # get data, amend, put back my $data = retrieve_fd(\*$fh); print 'item: ', $data->{item},$/; delete($data->{item}); print 'gone (error as expected): ', $data->{item},$/; truncate $fh, 0; # <- *** WAS MISSING THIS *** seek $fh, 0, 0; # <- *** WAS MISSING THIS *** store_fd($data, \*$fh); close($fh); #====== # now reload from the file my $check_data = retrieve($file); print 'why is this here? ', $check_data->{item},$/;

I am guessing its probably my understanding but cannot see why currently.

Thanks

Duncs


In reply to Storable or user bug? by duncs

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.