On Jan 1, 2008 2:12 PM, Chas. Owens <[EMAIL PROTECTED]> wrote:
snip
> > if I do the same in Perl (with a hard ref), do I have any guarantee
> > that the same behavior (implicit aliasing) does - or does not (every
> > new scalar is guaranteed to not alias the old non existant value) -
> > apply?
snip
> Saying my in Perl is like* saying
>
> struct scalar_struct* var = malloc(sizeof(struct scalar_struct));
>
> with the call to free() being handled for by the garbage collection
> system (when the number of references goes to zero).
>
> * this is not literal
snip

Of course, this does not mean you might not run into problems.  For
instance, the DBI module uses only one array (it is only my'ed once
for efficiency reasons) for each query when you use the fetch method*.
 So you cannot safely say

my @rows;
$sth->execute;
while (my $array_ref = $sth->fetch) {
     push @rows, $array_ref;
}
#all of the elements of @rows will be the same because $array_ref is
#always a reference to the same my'ed variable

You can deal with this by using the anonymous arrayref generator:

my @rows;
$sth->execute;
while (my $array_ref = $sth->fetch) {
     push @rows, [EMAIL PROTECTED];
}
#each element of @rows will be different
#because a new annonymous array was
#created by each call to [] and the contents
#of the array referenced by $array_ref were
#copied to it.

You can think of [] (when not being used as the offset operator) as
looking like this

sub anonymous_arrayref_generator {
    my @list = @_;
    return [EMAIL PROTECTED];
}

In general, you can expect anything returned to you is a new memory
address unless specifically documented as otherwise.

* from http://search.cpan.org/dist/DBI/DBI.pm#fetchrow_arrayref
       "fetchrow_arrayref"
             $ary_ref = $sth->fetchrow_arrayref;
             $ary_ref = $sth->fetch;    # alias

           Fetches the next row of data and returns a reference to an array
           holding the field values.  Null fields are returned as "undef" val‐
           ues in the array.  This is the fastest way to fetch data, particu‐
           larly if used with "$sth->bind_columns".

           If there are no more rows or if an error occurs, then
           "fetchrow_arrayref" returns an "undef". You should check
           "$sth->err" afterwards (or use the "RaiseError" attribute) to dis‐
           cover if the "undef" returned was due to an error.

           Note that the same array reference is returned for each fetch, so
           don't store the reference and then use it after a later fetch.
           Also, the elements of the array are also reused for each row, so
           take care if you want to take a reference to an element. See also
           "bind_columns".

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to