2

What I'm trying to do is use an Array of names to loop through several different Arrays. Here's what I have

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";
  }
}

This causes it to error out because it is attempting to look for an array named "@$Name" when what I want it to look for is "@Sensor1" "@Sensor2" & "@Sensor3".

1 Answer 1

12

My advice is to use a better data structure. For example:

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

Also see the classic from Mark Jason Dominus: Why it's stupid to `use a variable as a variable name'. The key point is summarized at the end of Part 3 as follows:

One of the biggest problems in all of compter programming is namespace management and data hiding. When you use a symbolic reference you are throwing away forty years of expensive lessons from the School of Hard Knocks.

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

1 Comment

Thanks a TON!!! I clearly need to spend more time working with hashes as this was such a simple solution.

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.