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.

In reply to Re: Module Readonly by calin
in thread Module Readonly by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.