Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
For my new Data::Reuse module (now on CPAN), I'm looking for a way to create a hash entry in which both the value as well as the key point to the same SV, or more general: set the hash key to a specific SV.

From what I've been able to learn from looking at a bunch of XS code, and [hs]v.[ch], the following code should do the trick:

#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" MODULE = Data::Reuse PACKAGE = Data::Reuse void key_as_sv( hv, key, val ) HV *hv SV *key SV *val PROTOTYPE: \%$$ CODE: SvREFCNT_inc(key); SvREFCNT_inc(val); STRLEN length = SvCUR(key); hv_store( hv, SvPV( key, length ), length , val, 0 ); HE *he = hv_fetch_ent( hv, key, 0, 0 ); HeSVKEY_set( he, key );

which would then be called thus:

my %hash; my $foo = 'foo'; Data::Reuse::key_as_sv( %hash, $foo, $foo ); print STDERR "found ".(keys %hash)." keys:\n"; print STDERR " $_: $hash{$_}\n" foreach keys %hash;

However, this produces the following output:

found 1 keys: foo:
or, in other words, the value of the key is gone.

I guess my question to any XS savvy Perl Monk is:

  • does it make sense to try to save memory this way?
  • if so, why doesn't the above work?

Thanks in advance for any insights.


In reply to Using SV as key in hash by liz

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others having an uproarious good time at the Monastery: (4)
    As of 2018-06-22 22:26 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (124 votes). Check out past polls.