On Mon, 10 Mar 2003, Steve Hay wrote:

> Hi,
>
> I have a hash which stores numerical data and I want to increase the
> values by variable amounts each time round a loop.
>
> At the moment, I am fetching the value to an SV, coercing that into an
> IV, increasing the value, and then making a new SV from that to store
> back into the hash:
>
> HV *hash;
> int total;
> int num;
> ...
> total = SvIV(*hv_fetch(hash, "total", 5, 0));
> total += num;
> hv_store(hash, "total", 5, newSViv(total), 0);

Something like (not tested):

#define H_CREAT 1
#define H_FETCH 0

SV **hval;
int  tot;
int  num;
...
hval = hv_fetch(hash, "total", 5, H_CREAT);
if( hval )
{
    if( SvOK(*hval) )
    {
        tot = SvIV(*hval) + num;
        sv_setiv(*hval, tot);
    }
    else
    {
        hv_store(hash, "total", 5, newSViv(num), 0);
    }
}

If you're fdoing this a lot, it may speed things up to precalculate
the hash with (iirc) the PERL_HASH macro.

Reply via email to