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

1
  • 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. Commented Dec 7, 2013 at 7:00

2 Answers 2

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 {} @).

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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;'
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.