in reply to dimensioning arrays

hi, after your replies (thanks) I'm thinking about this:
#/usr/bin/perl $nx=10; $ny=5; $initialisation = 0; foreach $i (0..$nx) { foreach $j (0..$ny) { $a[$i][$j] = $initialisation; } } $a[1][1] = 2; &subro($nx,\@a,$ny); sub subro($nx,\@a,$ny) { my $nx = shift; my @a = @{shift}; #should be wrong... my $ny = shift; print "$a[1][1]\n"; print "$nx\n"; print "$ny\n"; }
I saw the @{shift} use in some node around, but I get an error...
How do i fix it?
rob

Replies are listed 'Best First'.
Re: Re: dimensioning arrays
by Gloom (Monk) on Feb 16, 2001 at 16:31 UTC
    @{shift} may means @{'shift'} or @shift : it's ambiguous.

    be more sharp by adding "()" after shift.
    ... my $nx = shift; my @a = @{shift()}; # This should resolve your problem my $ny = shift; ...
    ________________________
    Hope this helps
      Thanks, Now it works.
      It would be nice for me to have a general subroutine
      sub initialise(\@dimensions,$initialisation_value,\@matrix)
      that gives back an initalised matrix of n-dimensions. I'll try as learning exercise, if it is not straightforward for someone to write it down here. There's a lot to learn from a snippet of code..:)
      rob
        This is a solution. Not very efficient though (sorry)... but I found it interesting.

        sub ar_init { my $shift = shift ; (defined $_[0]) ? [ map { ar_init(@_) } (1..$shift) ] : $shift ; } my $array_ref = ar_init(3, 2, 4, 'pop '); print $array_ref->[2][0][3]

        Since lists are 'flattened' in subroutine calls, you could put the dimensions in an array @dim = (3, 2, 4) and call it using ar_init(@dim, 'foo') - it would have the same effect. Note that the whole thing is constructed using references - you'll need to understand references for whatever solution you use. I like the explanation of reference syntax in _Effective_Perl_Programming_.