[vox-tech] perl question - arrays and lists

Samuel Merritt vox-tech@lists.lugod.org
Thu, 8 May 2003 13:17:01 -0700


--St7VIuEGZ6dlpu13
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, May 08, 2003 at 01:12:43PM -0700, Peter Jay Salzman wrote:
> there's some code i wrote that does something like:
>=20
> sub blah()
> {
>    foreach (@foobar)
>    {
>       push @array, ($foo, $bar);
>    }
>   =20
>    return @array;
> }
>=20
> so i'm returning an array whose elements are each a list of two items.

Actually, you're not. The documentation for "push" says:=20

Treats ARRAY as a stack, and pushes the values of LIST onto the end of
ARRAY.  The length of ARRAY increases by the length of LIST.

The above code is equivalent to:

foreach(@foobar)
{=20
    push @array, $foo;=20
    push @array, $bar;=20
}


> the receiving code is something like:
>=20
>    my @barfoo =3D blah();
>=20
> what i've found is that @barfoo is no longer an array of lists.  the
> lists appear to be "flattened out".
>=20
> so in the previous example, if there's one element of @foobar and $foo
> is "hello" and $bar is "dolly", then what i see is:
>=20
>    $barfoo[0] is "hello";
>    $barfoo[1] is "dolly";
>=20
> when what i really want is;
>=20
>    $barfoo[0] =3D ("hello", "dolly");
>=20
> i know that arrays can hold lists, but i must not be doing it correctly.
> do i need to do this with references?

Yep. Try push @array, [$foo, $bar].=20

--=20
Samuel Merritt
OpenPGP key is at http://meat.andcheese.org/~spam/spam_at_andcheese_dot_org=
.asc
Information about PGP can be found at http://www.mindspring.com/~aegreene/p=
gp/

--St7VIuEGZ6dlpu13
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)

iD8DBQE+urs9W3tuPJ1t7wURAkxWAJwP+byJJvJ4/c4ePWI0QIBwI4D/DACeJ7Zv
5R+sJS7Rtk6hALm4M8E9/Xo=
=lGOc
-----END PGP SIGNATURE-----

--St7VIuEGZ6dlpu13--