Data::Lock - makes variables (im)?mutable


Attribute-Constant documentation  | view source Contained in the Attribute-Constant distribution.

Index


NAME

Top

Data::Lock - makes variables (im)?mutable

VERSION

Top

$Id: Lock.pm,v 0.2 2008/06/27 19:50:52 dankogai Exp dankogai $

SYNOPSIS

Top

   use Data::Lock qw/dlock dunlock/;

   # note parentheses and equal

   dlock( my $sv = $initial_value );
   dlock( my $ar = [@values] );
   dlock( my $hr = { key => value, key => value, ... } );
   dunlock $sv;
   dunlock $ar; dunlock \@av;
   dunlock $hr; dunlock \%hv;

DESCRIPTION

Top

dlock makes the specified variable immutable like Readonly. Unlike Readonly which implements immutability via tie, dlock makes use of the internal flag of perl SV so it imposes almost no penalty.

Like Readonly, dlock locks not only the variable itself but also elements therein.

The only exception is objects. It does NOT lock its internals and for good reason.

Suppose you have a typical class like:

  package Foo;
  sub new     { my $pkg = shift; bless { @_ }, $pkg }
  sub get_foo { $_[0]->{foo} }
  sub set_foo { $_[0]->{foo} = $_[1] };

And

  dlock( my $o = Foo->new(foo=>1) );

You cannot change $o but you can still use mutators.

  $o = Foo->new(foo => 2); # BOOM!
  $o->set_foo(2);          # OK




If you want to make $o->{foo} immutable, Define Foo::new like:

  sub new {
      my $pkg = shift; 
      dlock(my $self = { @_ });
      bless $self, $pkg
  }

Or consider using Moose.

EXPORT

Top

Like List::Util and Scalar::Util, functions are exported only explicitly. This module comes with dlock and dunlock.

  use Data::Lock;                   # nothing imported;
  use Data::Lock qw/dlock dunlock/; # imports dlock() and dunlock()

FUNCTIONS

Top

dlock

  dlock($scalar);

Locks $scalar and if $scalar is a reference, recursively locks referents.

dunlock

Does the opposite of dlock.

SEE ALSO

Top

Readonly, perlguts, perlapi

AUTHOR

Top

Dan Kogai, <dankogai at dan.co.jp>

BUGS & SUPPORT

Top

See Attribute::Constant.

COPYRIGHT & LICENSE

Top


Attribute-Constant documentation  | view source Contained in the Attribute-Constant distribution.