in reply to Cache commands output

I'm not sure what you're asking, but it sounds as if you want either Cache::FileCache or Memoize.

Replies are listed 'Best First'.
Re^2: Cache commands output
by wangcong (Initiate) on Oct 20, 2008 at 15:36 UTC
    Thanks for your reply, kyle.

    What I want to cache is the output of some command, not a file, so that is not what I want. :)

      You can certainly cache the output of some command with Cache::FileCache.

      sub qx_cache { my $cmd = shift; my $cache = Cache::FileCache->new({ namespace => $0 }); die 'no cache' if ! $cache; my $out = $cache->get( $cmd ); if ( ! defined $out ) { $out = qx{ $cmd }; $cache->set( $cmd, $out ); } return $out; }

      You can set a timeout value when you call set(). Any get() on a key that's expired will come back undef.

        Thanks, everyone!

        I will try Cache::FileCache. :)
      I think kyle was right, what you want is Memoize

      This caches the result of a function by storring its return value in a hash, so the next time you call the function with the same parameters it will look up the return value in the hash and return that for you, rather then run the whole thing again.

      It also gives you the option to list the full hash so you can shove that in a file or database and load it again the next time you start your script resulting in lightning fast performance of a normally very slow fucntion, assuming you use the same input, which you must or caching makes no sense at all.

        One difference between using Memoize and Cache::FileCache is that the former defaults to caching forever while the latter can have an expiration time. The OP seems to be looking for some kind of expiration in the implementation. To do that with Memoize, I think you'd have to import unmemoize and write the expiration manually (but I could be wrong).

      I personally believe that this doesn't make sense, since the in root node you clearly say: "My idea is using temporary files for each command output, and use the time stamp of each file to know if that output is out of date or not." So basically it seems you want a form of caching/memoizing that is persistent across program invocations, and manages expiration dates. Cache::FileCache appears to do exactly this; in particular if you did care to read the very description "section" (it's one line!) of its documentation, then you would have found that:

      The FileCache class implements the Cache interface. This cache stores data in the filesystem so that it can be shared between processes.

      The additional emphasis is mine: please note that it talks about data which is agnostic wrt whered does it come from, be it a "command" or whatever...

      --
      If you can't understand the incipit, then please check the IPB Campaign.