Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Pre-caching large constants

by japhy (Canon)
on Feb 08, 2002 at 22:12 UTC ( [id://144260]=note: print w/replies, xml ) Need Help??


in reply to Pre-caching large constants

Here's Tie::Scalar::Once. It's not very complex.
# delays determination of a scalar's value until needed package Tie::Scalar::Once; require Exporter; @ISA = qw( Exporter ); @EXPORT = qw( delay ); use strict; sub delay { tie $_[0], __PACKAGE__, \$_[0], $_[1]; } sub TIESCALAR { my ($class, $var, $code) = @_; bless [ $var, $code ], $class; } sub FETCH { my ($self) = @_; my $val = $self->[1]->(); untie ${ $self->[0] }; ${ $self->[0] } = $val; } sub STORE { require Carp; Carp::croak("Can't store $_[1] to a constant"); } 1;
Use it like so:
use Tie::Scalar::Once; delay $x => sub { sqrt 2 }; # ... if ($you_need_to) { print $x }

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
Re: Re: Pre-caching large constants
by hossman (Prior) on Feb 09, 2002 at 22:34 UTC
    Acctually, it looks like a more elaborate version of this allready exists as Data::Lazy.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://144260]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-25 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found