2

Ok, so I got an array of an array (AoA) and I need to pass it to a subroutine, and then access it. This works… but is it strictly correct and indeed is there a better way that I should be doing this?

#!/usr/bin/perl
$a = "deep";
push(@b,$a);
push(@c,\@b);

print "c = @{$c[0]}\n";
&test(\@c);

sub test
{
    $d = $_[0];
    print "sub c = @{$$d[0]}\n";
}

Thanks

user3069232
  • 8,587
  • 7
  • 46
  • 87
  • 1
    Instead of `$d = $_[0]` I'd say `my ($d) = @_`. And in your `sub`, you should be able to say `$d->[0]->[0]` to dereference your AoA. – Joe Z Dec 07 '13 at 07:00

2 Answers2

3

The definitely better way to do it is to use strict; and use warnings; and to declare your variables before using them.

Also, you know that is not good practice to name your vars a or b - give them meaningful names, especially because the $a variable for example, is defined by the compiler (the one used with sort {} @).

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
  • Using meaningful names is always helpful, of course, but the `$a` variable is only predefined in the dynamic scope of a `sort` call. Defining global `$a` and `$b` variables poses no conflict with `sort`. – Tim Pierce Dec 07 '13 at 11:07
  • @qwrrty try this `perl -e 'use strict; use warnings; $a=1; print $a;'` and then try this `perl -e 'use strict; use warnings; $r=1; print $r;'` – Tudor Constantin Dec 07 '13 at 20:32
1
use strict;          # Always!
use warnings;        # Always!

sub test {
    my ($d) = @_;
    print "$d->[0][0]\n";

    # Or to print all the deep elements.
    for my $d2 (@$d) {
       for (@$d2) {
          print "$_\n";
       }
    }
}

{
   my $a = "deep";   # or:  my @c = [ [ "deep" ] ];
   my @b;
   my @c;
   push(@b,$a);
   push(@c,\@b);
   test(\@c);        # Can't pass arrays per say, just refs. You had this right.
}

Still needs better names. In particular, $a and $b should be avoided as they can interfere with sort.

ikegami
  • 367,544
  • 15
  • 269
  • 518