perl使用另一个变量(数组)调用变量名

时间:2019-06-26 16:12:32

标签: arrays perl

my @CLASS_TYPES = ("INTRA", "BB", "CAT");
my @INTRA_NEIGH = ("1.1.1.1/32","2.2.2.2/32");
my @BB_NEIGH = ("3.3.3.3/32","4.4.4.4/32" );
foreach my $class (@CLASS_TYPES) {
    my $csv = @.$class._NEIGH;
    print($csv);

当我打印$ csv时,我希望打印数组值我该如何实现

1 个答案:

答案 0 :(得分:3)

这不是正确的方法。参见Why it's stupid to `use a variable as a variable name'A More Direct Explanation of the Problem

@CAT_NEIGH不存在这一事实说明了部分问题。

解决方案:

my @CLASS_TYPES = ("INTRA", "BB", "CAT");
my %NEIGH = (
   INTRA => [ "1.1.1.1/32", "2.2.2.2/32" ],
   BB    => [ "3.3.3.3/32", "4.4.4.4/32" ],
);

for my $class (@CLASS_TYPES) {
   next if !$NEIGH{$class};

   print "$_\n" for @{ $NEIGH{$class} };
}

或者只是

my %NEIGH = (
   INTRA => [ "1.1.1.1/32", "2.2.2.2/32" ],
   BB    => [ "3.3.3.3/32", "4.4.4.4/32" ],
);

for my $class (keys(%NEIGH)) {
   print "$_\n" for @{ $NEIGH{$class} };
}