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.
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);
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);
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.
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.
&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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With