in reply to Module Readonly
Here are a few tricks with read-only scalar thingies. However, you say:
Constants have to put in variables, which makes the program vulnerable to side-effects unless the programmer can guarantee that the variable can never be assigned a new value, now or in the future, or in the hands of any other person who might pick up the program.
these tricks don't guarantee anything. There's no magic implementation of Digital Rights Management in Perl :-) (or anywere else for the matter).
1. Make dynamic scalar variable read-only (idiomatic)
$ perl *ro = \'readonly_dynamic'; print "=$ro=\n"; defined eval {$ro = 'newval'} or print "Exception: $@"; ^D =readonly_dynamic= Exception: Modification of a read-only value attempted at - line 4.
2. Make lexical scalar variable read-only (w/ Lexical::Alias)
$ perl use Lexical::Alias; # 5.8+, see pod my $ro; alias ${\'readonly_lexical'}, $ro; print "=$ro=\n"; defined eval {$ro = 'newval'} or print "Exception: $@"; ^D =readonly_lexical= Exception: Modification of a read-only value attempted at - line 8.
3. Make hash (or array) element read-only (w/ Array::RefElem)
$ perl use Array::RefElem qw/av_store hv_store/; hv_store %h, 'ro', ${\'readonly_hashval'}; av_store @a, 5, ${\'readonly_aryelem'}; print "=$h{ro}=$a[5]=\n"; defined eval {$h{ro} = 'newval'} or print "Exception: $@"; defined eval {$a[5] = 'newval'} or print "Exception: $@"; ^D =readonly_hashval=readonly_aryelem= Exception: Modification of a read-only value attempted at - line 7. Exception: Modification of a read-only value attempted at - line 9.
|
|---|