in reply to Re: Ini files
in thread Ini files

this:

for (keys(%{$ini{$hostnames[$i]}})) { push @slots,$_; push @ifindices,${$ini{$hostnames[$i]}}{$_}; }

how can I use it? $i is the variable inside the for loop (my $i). What I am trying to do is:

to associate slots with indices for every host (performance section, pop1 & pop2). The simplest way I thought was with an ini file (since I have worked before with ini files.)

Thanks!

Replies are listed 'Best First'.
Re^3: Ini files
by Sewi (Friar) on Sep 04, 2009 at 11:06 UTC
    $_ ist the default variable for loops, you don't need a special inside variable.
    If you got such a loop (and don't see any commands that could harm your computer), it's wise to
    for (keys(%{$ini{$hostnames[$i]}})) { print "Slot: $_\n"; push @slots,$_; print "IfIndex: ${$ini{$hostnames[$i]}}{$_}\n"; push @ifindices,${$ini{$hostnames[$i]}}{$_}; }
    This will show you what is happening.

    Let's split the lines: $hostname[$i] contains your hostname. This is used as a key for the %ini - hash. So we could simplify it for better understanding as

    for (keys(%{$Hostpart_from_INI})) {
    $Hostpart_from_INI contains a reference to what Config::INI found for this hostname (the one for the current loop run). It is a Hash-Reference, so we could also write:
    for (keys(%Host_Data_from_INI)) {
    Okay, now we're here with a simple Hash. Each loop run gets another key from the Hash %Host_Data_from_INI. If you got Problems with $_, we could add it:
    for $_ (keys(%Host_Data_from_INI)) {
    You should try the following for better understanding:
    perl -le 'for (1,2,3) { print $_; }'
    You could also add the $_ behind the for or you could use any other variable.
    Still with me? Okay, let's write your loop using the simplified form:
    for (keys(%Host_Data_from_INI)) { push @slots,$_; push @ifindices,$Host_Data_from_INI{$_}; }
    Remember: We changed nothing, the code is still the same. All we did was renaming things and solving references to show what Perl sees when executing the script.