perl kweschun

Victor Odhner plug-discuss@lists.plug.phoenix.az.us
Tue, 21 May 2002 14:14:28 -0700


"der.hans" wrote:
> $ perl -e '@a = "a"; print "$#a\n"; push( @a, @a ); print "$#a\n"; push( @a, "" ); print "$#a\n";'

Hans, please don't do Perl one-liners.  They make me dizzy.
Besides, they give Perl a bad name; I have to keep
explaining to people that I'm not THAT kind of Perl
programmer!

An empty *list* is a list with no values.
But an empty *string* is a value, so it increases the length
of the list.

When you push a list onto another list, or concatenate two
lists, what you get is a flat list with the total number of
elements that all of the lists contained.  So if you
concatenate two empty lists, for example, the result is
simply a list with no entries.  This can be a very nice
feature at times, but apparently for Roderick this is not
one of those times.

The normal behavior for Perl is that lists lose their
identity when concatenated, i.e., they just flatten out
into a single list.  Think of it as a container:  it
contains everything you've dumped into it, and nothing more.

Roderick Ford asked further:
> >  Or should I handle the indexing manually in those
> > cases where it is empty.  Sometimes my array
> > that I am pushing is empty, but I still want the
> > array to grow by one.

Since you mentioned "indexing", I'm guessing that you
plan to step through the list as an array, and you
want it possible to access "nothing" in element [n].

If "nothing" is something, and you WANT to add empty lists
to a list in Perl, you can make it a list of list REFERENCES.
This also makes nested lists possible.

If you're just pushing one thing at a time, rather than
a multi-entry array, then maybe Hans's example is your
solution:  instead of pushing lists, push strings.  Each
string, even an empty one, is a valid item.  So if the
'n'th string you pushed onto the list is empty but needs
to occupy @list[$n], then you need to use either scalars
or list-references.

Use list references if a given element may be a list
of zero, one, or multiple sub-elements.  That works nicely.

(Note that Python always does it this way:  A list is
an array of objects, not just the accumulation of their
values; so a Python list can contain empty lists as
separate elements.)

Vic