dars33
dars33

Reputation: 229

Perl assign variables to unknown number of array values

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!

Upvotes: 0

Views: 1073

Answers (2)

Eric Strom
Eric Strom

Reputation: 40142

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

Upvotes: 9

chaos
chaos

Reputation: 124277

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

Upvotes: 3

Related Questions