Paulster2 has asked for the wisdom of the Perl Monks concerning the following question:
I want to be able to dynamically update my hash. I am currently using the following to initialize it:
The first two lines of the code goes out and extracts data from a config file, that being server names and IP addresses. With the code shown I have to update it if the number of entries changes in the configuration file. I want to replace it with something like this:@Names = split(/\|/, &getIAMparameter(IAMNames)); @Ip = split(/\|/, &getIAMparameter(IAMIp)); %ServerStatus = ( "$Ip[$i]" => ["$Names[$i]", "unknown"], "$Ip[$i+1]" => ["$Names[$i+1]", "unknown"], "$Ip[$i+2]" => ["$Names[$i+1]", "unknown"], "$Ip[$i+3]" => ["$Names[$i+1]", "unknown"], "$Ip[$i+4]" => ["$Names[$i+1]", "unknown"] );
But only get one entry where there should be five. The $num = $#Ip; seems to work just fine, at least it gives me the number back that I am expecting, so I take it that there is something wrong with my foreach loop. I am by no means an expert at hashes (yes, I know, some consider it the life blood of perl!!). I was wondering if someone had a better mouse trap for me.@Names = split(/\|/, &getIAMparameter(IAMNames)); @Ip = split(/\|/, &getIAMparameter(IAMIp)); $num = $#Ip; foreach ($i=0;$i<=$num;$i++) { %ServerStatus = ( "$Ip[$i]" => ["$Names[$i]", "unknown"] ); }
Many thanks in advance.
Paulster2
You're so sly, but so am I. - Quote from the movie Manhunter.
UPDATE: Thanks for the typo correction, Joost, I have to retype stuff over from another system. That part of the code is typed correctly on that system. I just fat fingered it here. Also, as I stated previously, I have inherited this code from another perl monger who did not use strict. With a couple thousand lines of code, it would make it a little difficult to implement strict now. I try to almost strictly use strict (pun intended). Maybe I will take the time to go back and do that, it may be worth the time, even if for only a learning experience! Thanks again to all for your responses!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Initializing a hash using a foreach loop
by dragonchild (Archbishop) on Nov 29, 2004 at 19:34 UTC | |
Re: Initializing a hash using a foreach loop
by Roy Johnson (Monsignor) on Nov 29, 2004 at 19:37 UTC | |
Re: Initializing a hash using a foreach loop
by Zaxo (Archbishop) on Nov 29, 2004 at 19:40 UTC | |
Re: Initializing a hash using a foreach loop
by BrowserUk (Patriarch) on Nov 29, 2004 at 19:42 UTC | |
Re: Initializing a hash using a foreach loop
by Joost (Canon) on Nov 29, 2004 at 19:43 UTC | |
Re: Initializing a hash using a foreach loop
by gaal (Parson) on Nov 29, 2004 at 19:40 UTC |