From: dave on
I have trouble initializing the following multidimensional array

my @Table = ( [],[],[],[] );

push (@Table [ 't1', 't2', 't3', 't4' ] ) ;
push (@Table [ 'x1', 'x2', 'x3', 'x4' ] ); # and so on

foreach my $next (@Table)
{
if ( @$next[0] eq 'xx' )
{
# do something
}
}

When I run the foreach loop, the first 4 times will have "Use of
uninitialized value" error and then everything will be fine.
How can in initialize @Table so that the first entry should have 't1'
't2' .. .in it.

Thanks

David


From: J. Gleixner on
dave wrote:
> I have trouble initializing the following multidimensional array
>
> my @Table = ( [],[],[],[] );
No need to do that.

my @Table;

If you had:

use strict;
use warnings;

You'd see errors with your syntax for push:

>
> push (@Table [ 't1', 't2', 't3', 't4' ] ) ;
> push (@Table [ 'x1', 'x2', 'x3', 'x4' ] ); # and so on

perldoc -f push

" push ARRAY,LIST "


>
> foreach my $next (@Table)
> {
> if ( @$next[0] eq 'xx' )

That's not how you access the data.

$next->[0]

perldoc perlreftut

> {
> # do something
> }
> }
>
> When I run the foreach loop, the first 4 times will have "Use of
> uninitialized value" error and then everything will be fine.
> How can in initialize @Table so that the first entry should have 't1'
> 't2' .. .in it.

Really? Running your code I get:

Type of arg 1 to push must be array (not array slice) at - line 2, near
"] ) "
Type of arg 1 to push must be array (not array slice) at - line 3, near
"] )"
From: Sherman Pendley on
dave <davewu922(a)gmail.com> writes:

> I have trouble initializing the following multidimensional array
>
> my @Table = ( [],[],[],[] );
>
> push (@Table [ 't1', 't2', 't3', 't4' ] ) ;
> push (@Table [ 'x1', 'x2', 'x3', 'x4' ] ); # and so on
>
> foreach my $next (@Table)
> {
> if ( @$next[0] eq 'xx' )
> {
> # do something
> }
> }
>
> When I run the foreach loop, the first 4 times will have "Use of
> uninitialized value" error and then everything will be fine.

What else would you expect? The first thing you added to @Table was refs
to four empty arrays.

my @Table = ( [],[],[],[] );

Those array references aren't going away just because you push more onto
the end of @Table later on - they'll still be there.

> How can in initialize @Table so that the first entry should have 't1'
> 't2' .. .in it.

If you don't want four empty arrays to begin with, don't add them:

my @Table;

sherm--

--
My blog: http://shermspace.blogspot.com
Cocoa programming in Perl: http://camelbones.sourceforge.net