Re: Autovivification by foreach
- From: "A. Sinan Unur" <1usa@xxxxxxxxxxxxxxxxxxx>
- Date: Fri, 13 Mar 2009 12:17:42 GMT
Frank Seitz <devnull4711@xxxxxx> wrote in
news:71udaaFn4bctU1@xxxxxxxxxxxxxxxxxx:
Uri Guttman wrote:
"FS" == Frank Seitz <devnull4711@xxxxxx> writes:
FS> my (@a,$ref);
FS> push @a,@$ref;
FS> Perl throws an exception:
FS> Can't use an undefined value as an ARRAY reference
FS> Seems plausible.
FS> We are modifying the code:
FS> my (@a,$ref);
FS> push @a,$_ for @$ref;
FS> Now, there is no exception anymore. Perl creates the array on
the fly. FS> Why is it so? What is the difference?
in the first case @$ref is readonly as it is input to push and can't
be modified. autovivification only happens on lvalues when they are
undef and used where a ref should be.
....
This explanation is not plausible to me. Perl autovivifies before
loop start, because the loop might be modifying array elements?
How is this possible? The autovivificated array is empty.
It is clear that the body of the loop is never executed.
In my opinion it would make more sense when Perl would
throw an exception in this case too.
First, note that I do think this behavior is a little quirky.
However, it seems to me that autovivification in this context is useful.
It allows you to avoid writing code to check $ref before, say, adding
elements to some array for further processing. In that context, one may
not care about the definedness of $ref per se but only about if it
points to further elements to process.
Uri's explanation made sense to me. Hash element autovivification has
its quirks too but it is useful under similar circumstances.
If you don't want autovivification and you want to avoid the exception,
you can write:
push @a, @$ref if ref $ref eq 'ARRAY';
Or, if you want the exception, write:
die '$ref is not defined' unless defined $ref;
die '$ref is not an array ref' unless ref $ref eq 'ARRAY';
Sinan
--
A. Sinan Unur <1usa@xxxxxxxxxxxxxxxxxxx>
(remove .invalid and reverse each component for email address)
comp.lang.perl.misc guidelines on the WWW:
http://www.rehabitation.com/clpmisc/
.
- References:
- Autovivification by foreach
- From: Frank Seitz
- Re: Autovivification by foreach
- From: Uri Guttman
- Re: Autovivification by foreach
- From: Frank Seitz
- Autovivification by foreach
- Prev by Date: Re: Creating an Active Directory group using Net::LDAP
- Next by Date: FAQ 9.12 How do I put a password on my web pages?
- Previous by thread: Re: Autovivification by foreach
- Next by thread: Re: Autovivification by foreach
- Index(es):
Relevant Pages
|