in reply to Dereferencing woes

You don't get a copy when you dereference an array ref. But perhaps you're thinking of the anonymous array constructor, which will create a copy.

For example:

my @array = ( 1, 2, 3 ); my $aref = \@array;

The above example doesn't create a copy of @array. But the following will:

my @array = ( 1, 2, 3 ); my $aref = [ @array ];

This may be desirable behavior. There are times, for example, where you really do need a copy to be made so that you're pointing to a new array rather than to the old one.

Another construct to consider when using hashes is using keys in list context. For example:

foreach my $key ( keys %hash ) { ........ }

IIRC, keys in list context will create a list of the keys, which means that in addition to your hash, you've also got in memory a temporary list of its keys; that could be a memory hog. If that's a concern, use the while ( my( $key, $val ) = each %hash ) { ........ } construct, since this shouldn't cause a list to be generated.

So as the previous followup suggest, don't worry about it, it's not creating a copy.

You do have to be concerned with things like sort though. Even if you're saying @array = sort @array sort is probably creating a temporary list somewhere to assign to @array. The assignment is done in one fell swoop, so the entire list must be created first.


Dave

Replies are listed 'Best First'.
Re: Re: Dereferencing woes
by dave_the_m (Monsignor) on May 05, 2004 at 21:03 UTC
    Even if you're saying @array = sort @array sort is probably creating a temporary list somewhere to assign to @array.
    From Perl 5.8.4 onwards, that particular construct is optimised to sort the array in-place, so no copying is done.