0

I have a sub routine that creates an array of IP addresses, however I do not know how many IPs will be pushed into the array. (based on how many matches in a txt file) Then I have another sub that needs to pull each IP address from the array and assign a variable. all IPs will be printed in the same line of output. I want to do something like this:

@IPS = ("1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4");  
print "vserver1 $IPS[0], vserver2 $IPS[1], vserver3 $IPS[2], vserver4 $IPS[3]\n";    

The problem is, I won't know how many IPs will be in the array. How do I call an unknown number of values? Is it possible to assign a variable to the first IP, then the same variable assigned to the second IP the next time I call it?

print "vserver1 $IPS, vserver2 $IPS, vserver3 $IPS, vserver4 $IPS\n";  

thanks in advance!

2 Answers 2

9

It is technically possible to do what you are asking, but it is not a good solution for this problem. Because even if a magic $IPS variable would walk along the array with each access, you would still not have the vserver# portion of your output.

Instead, why not write a loop to process the array:

print join(', ' => map {"vserver$_ $IPS[$_ - 1]"} 1 .. @IPS ), "\n";
Sign up to request clarification or add additional context in comments.

Comments

3
my @items;
my $index;
foreach my $ip (@IPS) {
    $index++;
    push @items, "vserver$index $ip";
}
print join(', ', @items), "\n";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.