wilfrieds
asked on
Pushing associative arrays
I'm trying to push variables in an associative array, then, with each iteration of the loop, search the array for a particular value. If I found the value, I want to see what its "association" looks like.
This is the code :
if ($elapsed>0.02) { # I measure something before this
# in the following line I want to check the assoc. array # SLOWHOSTS for a particular ipaddress
foreach $ip (sort keys(%SLOWHOSTS)) {
# if it exists I want to check its association which is
# in a variable called $elapsed
if (/$ipaddress/) { ????; }
# if the ipaddress is not found, I want to add it to the
# associative array with the value of $elapsed so that
# I get something like %SLOWHOSTS=(192.168.0.1,45 )
# I tried a lot of variations like push() and the next one
# but nothing seems to work for me
%SLOWHOSTS .= $ipaddress . ',' . $elapsed;
&AlertSpeed;
}
}
This is the code :
if ($elapsed>0.02) { # I measure something before this
# in the following line I want to check the assoc. array # SLOWHOSTS for a particular ipaddress
foreach $ip (sort keys(%SLOWHOSTS)) {
# if it exists I want to check its association which is
# in a variable called $elapsed
if (/$ipaddress/) { ????; }
# if the ipaddress is not found, I want to add it to the
# associative array with the value of $elapsed so that
# I get something like %SLOWHOSTS=(192.168.0.1,45
# I tried a lot of variations like push() and the next one
# but nothing seems to work for me
%SLOWHOSTS .= $ipaddress . ',' . $elapsed;
&AlertSpeed;
}
}
if( !exists($SLOWHOSTS{$ipaddr es}) ){
$SLOWHOSTS{$ipaddres} = $elapsed;
&AlertSpeed;
}
$SLOWHOSTS{$ipaddres} = $elapsed;
&AlertSpeed;
}
ASKER
Thanks. It works, only, I fail to see why it must be so different from normal arrays; or am I missing something?
Anyway, if you want to grab the points, mark it as an answer.
Anyway, if you want to grab the points, mark it as an answer.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#it's not so different
$array[3]=$elapsed;
$hash{'three'}=$elapsed;
#you could even say
@array=(@array,$elapsed);
%hash=(%hash,'three',$elap sed);
#although that would be silly.
$HASH{$ip} ||= $elapsed; #would also work, assuming $elapsed is true
$array[3]=$elapsed;
$hash{'three'}=$elapsed;
#you could even say
@array=(@array,$elapsed);
%hash=(%hash,'three',$elap
#although that would be silly.
$HASH{$ip} ||= $elapsed; #would also work, assuming $elapsed is true
if (! exists($HASH{$ip})) {
# The IP does not exist
$HASH{$ip} = $elapsed;
}; # else it does not...