我要做的是使用一个名称数组来遍历几个不同的数组。这就是我所拥有的
my @Sensor1 = ("1.2.3.4","1.2.3.5","1.2.3.6");
my @Sensor2 = ("2.2.2.1","2.2.2.2","2.2.2.3");
my @Sensor3 = ("128.0.0.1","128.0.0.2","128.0.0.3");
my @Names = ("Sensor1","Sensor2","Sensor3");
my ($Name, $IP);
foreach $Name (@Names){
foreach $IP (@$Name){
print "$Name"," $IP","\n";
}
}
这导致它出错,因为它试图寻找名为“@ $ Name”的数组,当我想要它寻找的是“@ Sensor1”“@ Sensor2”& “@传感器3”。
答案 0 :(得分:12)
我的建议是使用更好的数据结构。例如:
use strict;
use warnings;
my %sensors = (
Sensor1 => ['1.2.3.4', '1.2.3.5', '1.2.3.6'],
Sensor2 => ['2.2.2.1', '2.2.2.2', '2.2.2.3'],
Sensor3 => ['128.0.0.1','128.0.0.2','128.0.0.3'],
);
for my $sensor_name (sort keys %sensors){
my $ips = $sensors{$sensor_name};
print "$sensor_name: $_\n" for @$ips;
}
另见Mark Jason Dominus的经典:Why it's stupid to `use a variable as a variable name'。关键点在第3部分末尾概述如下:
所有人中最大的问题之一 compter编程是名称空间 管理和数据隐藏。当你 使用你的象征性参考 扔掉四十年的昂贵 硬学院的经验教训 爆震。