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

Hey, folks. I'm curious about an issue I've observed with trying to copy a tied array. In this particular case, the tie (this tie) causes the array to expand as it is looked at. What I observe happening however is that when trying to copy the tied array
@copy = @tied;
The results are functionally equivalent to
my $length = $#tied; @copy[0..$length] = @tied[0..$length];
as opposed to (what I'd more expect):
@copy = (); push @copy, $_ for @tied;
I've seen this on both 5.005 and 5.6.1 (but haven't tried 5.8).

So the question really is: is this how it should be? Is it my own stupid fault for implementing a FETCH method that actually alters the size of the tied array? If so, it should probably be explicitly documented that this is bad form. Really, I suppose that the best possible thing might be to add a FETCHALL method to the tiearray interface. Certainly, most array ties would define FETCHALL to be

sub FETCHALL { $self = shift; map { $self->FETCH[$_] } 0..$self->FETCHSIZE; }
but it would be nice to be able to override it when necessary.

Anyway, I'm just curious. Thanks.

--

For anyone curious, though, this really does not interfere with how r.pm works... at least not for perl -mr -n ... (or perl -mr -p) type stuff... since the <> operator really functions like it is shifting the contents of @ARGV, not copying the array. Also, I know that I haven't "officially" released r.pm, yet, as I'm still wading through legal processes with my employer, with respect to who owns what IP, and what they would let me do with it, etc.

Replies are listed 'Best First'.
Re: Copying a tied array
by Zaxo (Archbishop) on Jun 16, 2004 at 19:32 UTC

    When FETCH() modifies the array, you should expect the unexpected. It's not necessarily wrong, but it doesn't fit perl's or anybody else's model of how arrays should act.

    After Compline,
    Zaxo

Re: Copying a tied array
by dave_the_m (Monsignor) on Jun 17, 2004 at 10:25 UTC
    So the question really is: is this how it should be?
    If it's not documented how perl does it, then you can't make any assumptions about how it does it (or how it might do it in the future).
    Is it my own stupid fault for implementing a FETCH method that actually alters the size of the tied array?
    Yes ;-)
    Really, I suppose that the best possible thing might be to add a FETCHALL method to the tiearray interface.
    No, that would be a BAD idea. All sorts of horrible things start happening in the face of inheritance, eg where someone subclasses a CPAN tied module and overrides FETCH, then a new version of the CPAN module is released that implements the "optional" FETCHALL method, and suddenly the user's own FETCH method is no longer being called. It's for this reason that things like FETCHSLICE haven't been implemented.

    Dave.