Reputation: 8995
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
Upvotes: 2
Views: 118
Reputation: 386676
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
.
Upvotes: 1
Reputation: 26871
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 {} @
).
Upvotes: 3