Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I would like to lock the contents of an array similar to what is available for hashes with lock_hash() in Hash::Util. I don't see anything equivalent in List::Util, and the Perl Cookbook only discusses scalar values.

Do you have any suggestions? Thanks.

Replies are listed 'Best First'.
Re: locking arrays?
by davido (Cardinal) on Nov 28, 2003 at 01:30 UTC
    I was looking on CPAN for something else and stumbled across just the module you're looking for: Readonly.

    The POD's first line says:

    Readonly - Facility for creating read-only scalars, arrays, and hashes.

    use Readonly; Readonly::Array my @arr => @values;

    It appears to be just that easy. Read the POD though. Apparently there is a considerable speed-performance hit. The POD states that if you can also install the Readonly::XS module on your system, the performance hit is substantially mitigated.

    Hope this helps!


    Dave


    "If I had my life to live over again, I'd be a plumber." -- Albert Einstein
Re: locking arrays?
by davido (Cardinal) on Nov 27, 2003 at 22:34 UTC
    You may be able to use Tie::Array to tie the array to an object. Using Tie::StdArray you can selectively overload the object methods that can act upon the tied array.

    It's probably not trivial to dive into all that for the first time (I haven't done it myself). But it looks like the tools are all there for the using.

    From the Tie::Array POD:

    The Tie::StdArray package provides efficient methods required for tied arrays which are implemented as blessed references to an "inner" perl array. It inherits from Tie::Array, and should cause tied arrays to behave exactly like standard arrays, allowing for selective overloading of methods.

    I hope this gets you going in the right direction.


    Dave


    "If I had my life to live over again, I'd be a plumber." -- Albert Einstein
Re: locking arrays?
by ysth (Canon) on Nov 27, 2003 at 22:41 UTC
    Cough. require 5.008; Internals::SvREADONLY(@array, 1) will prevent you from adding any elements beyond the highest one ever used. But you didn't hear me say it.

    (Update: also prevents @array = ... or delete $array[...], even if they refer to existing elements.)