dlock()をData::Lockとして分離し、それを使ってAttributeでRead-onlyを実現しています。
Source
かのごとく短し。lvalueと三項演算子で遊んでます。Pure Perlです。PODはsignatureの後。
Data::Lock
package Data::Lock;
use 5.008001;
use warnings;
use strict;
our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g;
use Attribute::Handlers;
use Scalar::Util ();
use base 'Exporter';
our @EXPORT_OK = qw/dlock dunlock/;
for my $locked ( 0, 1 ) {
my $subname = $locked ? 'dlock' : 'dunlock';
no strict 'refs';
*{$subname} = sub {
if ( !Scalar::Util::blessed( $_[0] ) ) {
my $type = ref $_[0];
for (
$type eq 'ARRAY' ? @{ $_[0] }
: $type eq 'HASH' ? values %{ $_[0] }
: $type ne 'CODE' ? ${ $_[0] }
: ()
)
{
dlock($_) if ref $_;
Internals::SvREADONLY( $_, $locked );
}
$type eq 'ARRAY' ? Internals::SvREADONLY( @{ $_[0] }, $locked )
: $type eq 'HASH' ? Internals::SvREADONLY( %{ $_[0] }, $locked )
: $type ne 'CODE' ? Internals::SvREADONLY( ${ $_[0] }, $locked )
: undef;
}
Internals::SvREADONLY( $_[0], $locked );
};
}
1;
Attribute::Constant
package Attribute::Constant;
use 5.008001;
use warnings;
use strict;
our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g;
use Attribute::Handlers;
use Data::Lock ();
sub UNIVERSAL::Constant : ATTR {
my ( $pkg, $sym, $ref, $attr, $data, $phase ) = @_;
(
ref $ref eq 'HASH' ? %$ref
: ref $ref eq 'ARRAY' ? @$ref
: ($$ref)
) = ref $data
? ref $data eq 'ARRAY' ? @$data # perl 5.10.x
: $data : $data; # perl 5.8.x
Data::Lock::dlock($ref);
}
1;
気がついたこと
行をまたがるAttributeって、Perl 5.8.xだと駄目なんですねえ。
my $o : Constant(Foo->new(1,2,3)) # ok;
my $p : Constant(Bar->new(
1,2,3
)
) # needs Perl 5.10
この場合は、Data::Lock::dlock()を代わりに使うことができます。
dlock(my $p = Bar->new(
1, 2, 3
));
Read-onlyな変数(variable)、すなわち定数(constant)というのは、文字通りコンスタントに使われます。ベンチマークを見てもらえばわかりますが、何万回もアクセスするような変数で30倍のペナルティというのは痛いですよね。特に数値計算とか。これを使えばペナルティはほぼゼロです。
Enjoy!
Dan the Perl Monger, Constantly
perldoc Data::Lock
NAME
Data::Lock - makes variables (im)?mutable
VERSION
$Id: Lock.pm,v 0.2 2008/06/27 19:50:52 dankogai Exp dankogai $
SYNOPSIS
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
"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
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
dlock
dlock($scalar);
Locks $scalar and if $scalar is a reference, recursively locks
referents.
dunlock
Does the opposite of "dlock".
SEE ALSO
Readonly, perlguts, perlapi
AUTHOR
Dan Kogai, "<dankogai at dan.co.jp>"
BUGS & SUPPORT
See Attribute::Constant.
COPYRIGHT & LICENSE
Copyright 2008 Dan Kogai, all rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
perldoc Attribute::Constant
NAME
Attribute::Constant - Make read-only variables via attribute
VERSION
$Id: Constant.pm,v 0.2 2008/06/27 19:50:52 dankogai Exp dankogai $
SYNOPSIS
use Attribute::Constant;
my $sv : Constant( $initial_value );
my @av : Constant( @values );
my %hv : Constant( key => value, key => value, ...);
DESCRIPTION
This module uses Data::Lock to make the variable read-only. Check the
document and source of Data::Lock for its mechanism.
ATTRIBUTES
This module adds only one attribute, "Constant". You give its initial
value as shown. Unlike Readonly, parantheses cannot be ommited but it is
semantically more elegant and thanks to Data::Lock, it imposes almost no
performance penalty.
CAVEAT
Multi-line attributes are not allowed in Perl 5.8.x.
my $o : Constant(Foo->new(1,2,3)) # ok;
my $p : Constant(Bar->new(
1,2,3
)
) # needs Perl 5.10
In which case you can use Data::Lock instead:
dlock(my $p = Bar->new(
1, 2, 3
));
After all, this module is a wrapper to Data::Lock;
BENCHMARK
Here I have benchmarked like this.
1. Create an immutable variable.
2. try to change it and see if it raises exception
3. make sure the value stored remains unchanged.
See t/benchmark.pl for details.
Simple scalar
Rate Readonly glob Attribute
Readonly 7803/s -- -97% -97%
glob 281666/s 3510% -- -5%
Attribute 295780/s 3691% 5% --
Array with 1000 entries
Rate Readonly Attribute
Readonly 8589/s -- -97%
Attribute 278755/s 3145% --
Hash with 1000 key/value pairs
Rate Readonly Attribute
Readonly 6979/s -- -97%
Attribute 207526/s 2874%
SEE ALSO
Data::Lock, constant
AUTHOR
Dan Kogai, "<dankogai at dan.co.jp>"
BUGS
Please report any bugs or feature requests to "bug-attribute-constant at
rt.cpan.org", or through the web interface at
<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Attribute-Constant>. I
will be notified, and then you'll automatically be notified of progress
on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Attribute::Constant
You can also look for information at:
* RT: CPAN's request tracker
<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Attribute-Constant>
* AnnoCPAN: Annotated CPAN documentation
<http://annocpan.org/dist/Attribute-Constant>
* CPAN Ratings
<http://cpanratings.perl.org/d/Attribute-Constant>
* Search CPAN
<http://search.cpan.org/dist/Attribute-Constant>
ACKNOWLEDGEMENTS
Readonly
COPYRIGHT & LICENSE
Copyright 2008 Dan Kogai, all rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
このブログにコメントするにはログインが必要です。
さんログアウト
この記事には許可ユーザしかコメントができません。