http://www.perlmonks.org?node_id=802002

pelagic has asked for the wisdom of the Perl Monks concerning the following question:

Hell Monks, this short example of mine tries to store the 'memory' of the Module memoize in a file but it segfaults.
use strict; use Memoize; use Memoize::Storable; my $filename = './memory.tmp'; tie my %cache => 'Memoize::Storable', $filename; memoize 'function', SCALAR_CACHE => [HASH => \%cache]; print function(1), "\n"; print function(1), "\n"; print function(1), "\n"; print function(2), "\n"; sub function { my $wtf = shift; print "I am the function\n"; return 'anything'; }
and says:
# perl memo I am the function anything anything anything I am the function anything Segmentation fault #
Any ideas?

pelagic

Replies are listed 'Best First'.
Re: Memoize::Storable produces 'Segmentation fault'
by gmargo (Hermit) on Oct 19, 2009 at 15:32 UTC

    UPDATE: Code fixed below. The problem was the calls to function() are called in list context, therefore Memoize stores it in a list cache, separate from the scalar cache. Adding an empty string before the function call forces a scalar context.

    The segfault went away when I added an unmemoize. But on the second run, it calls the function again instead of using the supposedly cached data in memory.tmp.

    #!/usr/bin/perl use strict; use warnings; use diagnostics; use Memoize qw(memoize unmemoize); use Memoize::Storable; my $filename = './memory.tmp'; tie my %cache => 'Memoize::Storable', $filename; memoize 'function', SCALAR_CACHE => [HASH => \%cache]; print "".function(1), "\n"; print "".function(1), "\n"; print "".function(2), "\n"; # Changed original order print "".function(1), "\n"; unmemoize 'function'; sub function { my $wtf = shift; print "I am the $wtf function\n"; return "anything $wtf"; }

    First run results:

    I am the 1 function anything 1 anything 1 I am the 2 function anything 2 anything 1

    Second run results:

    anything 1 anything 1 anything 2 anything 1

      Great help gmargo, thank you very much!

      pelagic
Re: Memoize::Storable produces 'Segmentation fault'
by Anonymous Monk on Oct 19, 2009 at 15:12 UTC
    Upgrade Storable, upgrade Memoize::Storable :)