I want to implement an array of arrays (2-dimensional array).
I have a @bigary and several @smallary 's.
I push each smallary onto the bigary.
Then, I use a foreach statment on the bigary
foreach @temp (@bigary)....
Then, I want to grab the first element in temp. My question is:
Should I declare temp to be a string or an array (neither has worked
so far). What would be a better way to implement this?
Thanks for any help to a Perl newbie :-)
Howard
I think you want
foreach $temp (@bigary) {
local ($first) = $$temp[0];
local (@smallary) = @$temp;
...
}
I suppose $$temp[0] should really be $$temp[$[] or something like that.
There's probably a faster way to do this. OtherTom? :_)
Tom
You can't put an @-array into another @-array, not even in perl5.
An array is a list of scalars, as it always has been. The new thing
is that a scalar can be a *reference* to something else: another
scalar, an array or a hash. So, if you do
push @bigarray, @smallaray
all you do is add the values of @smallarray to the end of @bigarray.
Instead you should
push @bigarray, \@smallarray
The `\' in front of @smallarray creates a reference, which is just
another scalar.
>Then, I use a foreach statment on the bigary
>
> foreach @temp (@bigary)....
>
>Then, I want to grab the first element in temp. My question is:
>Should I declare temp to be a string or an array (neither has worked
>so far).
A scalar, that is you should have $temp instead of @temp. To dereference
$temp, i.e. to access the @smallarray that hides behind the reference,
say @$temp, as in
foreach $element ( @$temp ) { ...
A little demo follows below.
Anno
#!/usr/local/bin/perl
@small1 = qw( a b c d);
@small2 = qw( e f g h);
@big = ( \@small1, \@small2);
foreach $temp ( @big ) {
foreach $element ( @$temp ) {
print "$element ";
}
print "\n";
}
I'd have written that:
@bigary = (
[ 1 .. 10 ],
[ 10 .. 19 ],
[ 20 .. 29 ],
);
foreach $temp (@bigary) {
my $first = $temp->[0];
my @smallary = @$temp;
print "first is $first\n";
print "smallary is @smallary\n";
}
:I suppose $$temp[0] should really be $$temp[$[] or something like that.
No, we probably shouldn't have to deal with that anymore.
--tom
--
Tom Christiansen Perl Consultant, Gamer, Hiker tch...@mox.perl.com
Perl programming is an *empirical* science!
--Larry Wall in <10...@jpl-devvax.JPL.NASA.GOV>
You *certainly* don't have to deal with that anymore, if you don't want
to. The setting of $[ in one file can no longer have any effect on the
array base in another file. In fact, if you use $[ in a file that
hasn't set $[, the lexer itself inserts a 0 instead of $[, so the
compiler never even sees it. So you might as well put the 0 yourself.
$[ is moribund and quarantined. Pretend it doesn't exist, and go about
your life.
Larry