簡體   English   中英

使用perl將數組的數組傳遞給子例程

[英]Passing an Array of an Array to a subroutine using perl

好的,所以我得到了數組(AoA)的數組,我需要將其傳遞給子例程,然后再訪問它。 這行得通……但是嚴格來說這是正確的嗎,確實有更好的方法可以使我這樣做嗎?

#!/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";
}

謝謝

絕對更好的方法是use strict; use warnings; 並在使用它們之前聲明變量。

另外,您知道將vars命名為ab並不是一種好習慣-給它們命名是有意義的,尤其是因為$a變量是由編譯器定義的(用於sort {} @ $a變量)。

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.
}

仍然需要更好的名字。 特別要避免$a$b因為它們會干擾sort

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM