Link to home
Start Free TrialLog in
Avatar of wilfrieds
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;
}
}
Avatar of olthoff
olthoff

I assume that you have an IP already.  You seem to be checking the SLOWHOSTS ip's to see if they exist, and they will.  This is the code to see if the IP does not exist and add it.

if (! exists($HASH{$ip})) {
  # The IP does not exist
  $HASH{$ip} = $elapsed;
}; # else it does not...

Avatar of ozo
if( !exists($SLOWHOSTS{$ipaddres}) ){
     $SLOWHOSTS{$ipaddres} = $elapsed;
     &AlertSpeed;
}
Avatar of wilfrieds

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.
ASKER CERTIFIED SOLUTION
Avatar of olthoff
olthoff

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
#it's not so different
$array[3]=$elapsed;
$hash{'three'}=$elapsed;

#you could even say
@array=(@array,$elapsed);
%hash=(%hash,'three',$elapsed);
#although that would be silly.

$HASH{$ip} ||= $elapsed;  #would also work, assuming $elapsed is true