in reply to Use constant vs. hashes

Another solution might be to protect ordinary scalars using a tie:

use strict; package ConstantScalar; use Carp; require Tie::Scalar; @ConstantScalar::ISA = 'Tie::StdScalar'; sub STORE { confess "illegal store into constant"; } # call with a list of refs to scalars sub makeConstant { while (my $ref = shift) { (warn "nonscalar ref", next) if (ref($ref) ne 'SCALAR'); tie $$ref, 'ConstantScalar', $$ref; } } package main; my ($A, $B, $C, $D) = (1, 2, 3, 4); my $E = 5; print "$A $B $C $E\n"; ConstantScalar::makeConstant(\($A, $B, $C, $D)); $E = 123; $A = 4; # illegal store into constant $B = 5; print "$A $B $C $E\n";

Replies are listed 'Best First'.
Re: Re: Use constant vs. hashes
by repson (Chaplain) on Jul 03, 2001 at 10:20 UTC
    This is one I developed seperately with more stuff in it, also allowing constant hashes and arrays (much like tuples in python as I understand them). It also uses a different and IMHO cleaner syntax for creating the constants:
    Const my $foo => 42;

    Here's the sample program:

    #!/usr/bin/perl -w use strict; use Const qw/Const ConstHash ConstArray/; Const my $FOO => 42; # tie my $FOO, 'Const', 42; print "$FOO\n"; # prints "42" $FOO = 43; # croaks for attempted change $FOO++; # same ConstHash my %BOO => { foo => 'blah', moo => 41, 2 => 'no' }; # tie my %BOO, 'ConstHash', { foo => 'blah', moo => 41, 2 => 'no' }; print "$BOO{foo} $BOO{2}\n"; # prints "blah no" $BOO{moo}++; # croaks for attempted change %BOO = (); # same print "$BOO{Foo}\n"; # croaks for non-existant element ConstArray my @MOO => [ qw/foo 2 five seven/ ]; # tie my @MOO, 'ConstArray', [ qw/foo 2 five seven ]; print "$MOO[0] $MOO[3]\n"; # prints "foo seven" $MOO[1]++; # croaks for attemped change $MOO[5] = 2; # same splice(@MOO,1,1,4); # same again print "$MOO[10]\n"; # croaks for non-existant element
    And the implementation in Const.pm (click Read More)
      Thanks to everyone - some great ideas here. And, as I'd hoped, a couple that I hadn't thought of :)
      --
      man with no legs, inc.
Re: Re: Use constant vs. hashes
by frag (Hermit) on Jul 03, 2001 at 09:41 UTC
    ++{the idea}, but here's another WTDI.
    package Fixed; use Carp; use strict; sub TIESCALAR { my ($class, $value) = @_; croak "No value provided for new Fixed scalar" unless defined $value; bless \$value, $class; } sub FETCH { return ${$_[0]}; } sub STORE { croak "Illegal assignment to Fixed scalar"; } package main; tie my $v, "Fixed" => "32"; tie my $x, "Fixed" => "0"; tie my $str, "Fixed" => "my string"; print ">> $v\n"; $v++; print ">> $v\n";

    -- Frag.