Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store null in Perl hash

Tags:

perl

xs

I want to use Perl hash in my C code (XS) as a set, so I only need to keep keys in hash. Is it possible to store something like null or another constant value to avoid creating unnecessary value?

Something like this:

int add_value(HV *hash, SV *value)
{
    // just an example of key
    char key[64];
    sprintf(key, "%p", value);
    if (hv_exists(hash, key, strlen(key)) return 0;

    // here I need something instead of ?
    return hv_stores(hash, key, ?) != NULL;
}

One of possible solution could be to store value itself, but maybe there is special constant for undef or null.

like image 850
John Tracid Avatar asked Aug 05 '15 15:08

John Tracid


People also ask

How do I declare an empty hash in Perl?

This command will declare an empty hash: my %hash; Similar to the syntax for arrays, hashes can also be declared using a list of comma separated values: my %weekly_temperature = ('monday', 65, 'tuesday', 68, 'wednesday', 71, 'thursday', 53, 'friday', 60);

How do I undef a hash in Perl?

undef on hash elements The script uses $h{Foo} = undef; to set the value of a hash key to be undef. use strict; use warnings; use Data::Dumper qw(Dumper);

How do I empty a hash array in Perl?

Empty values in a Hash: Generally, you can't assign empty values to the key of the hash. But in Perl, there is an alternative to provide empty values to Hashes. By using undef function. “undef” can be assigned to new or existing key based on the user's need.

How do I initialize a hash in Perl?

Regular way of initializing a hash :my %h1=("Jan" => 31, "Feb" => 28, "Mar" => 31); This is the normal way of populating hash where-in every set is a key-value pair. The operator separating the key-value pair '=>' is called Fat-comma operator.


1 Answers

&PL_sv_undef is the undefined value, but you can't, unfortunately, use it naively in hashes and arrays. Quoting perlguts:

Generally, if you want to store an undefined value in an AV or HV, you should not use &PL_sv_undef , but rather create a new undefined value using the newSV function, for example:

av_store( av, 42, newSV(0) );
hv_store( hv, "foo", 3, newSV(0), 0 );
like image 198
pilcrow Avatar answered Oct 14 '22 10:10

pilcrow