Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- rename key
- George Mpouras
May 12, 2015, 10:30 pm
rate this thread
Re: rename key
GM> On 13/5/2015 01:55, firstname.lastname@example.org wrote:
>>> is there any internal hack to rename a hash key (without ref to it) ?
>> $myhash = $myhash;
>> delete $myhash;
>> should do the job quite nicely.
GM> yes it will; the drawback is that copy the data and this takes times.
do you understand that hashes don't know about copies or whatever. if
your data is large, then use a ref to it instead of copying the data
around. that way you can pass it to subs as well. only when you process
the data will you need to dereference it (and that doesn't copy it).
my $foo = 'large data' ;
$bar = $foo ;
$bar = delete $bar ;
renamed the key without expensive copy
Re: rename key
It's not possible to change the 'name' of a hash key as this name is the
Ultra-condensed, simplified description: A 'hash table' is an array
of linked lists. An arithemtic transformation is performed on the key to
turn it to an index into this array and both value and key are then put
onto this list. On lookup, the same transformation is performed
on the key whose value (if any) is supposed to be determined and
the list found in this way is then searched for a matching key.
It's possible to re-associated the SV (scalar) associated with a certain
hash key with a different key using the perl C api, eg, this xs function
/* includes */
MODULE = hash_move
hash_move(hv, to, from)
SV *v, **rc;
char *t_key, *f_key;
STRLEN t_key_len, f_key_len;
f_key = SvPV(from, f_key_len);
rc = hv_fetch(hv, f_key, f_key_len, 0);
if (!rc) XSRETURN_YES;
v = *rc;
t_key = SvPV(to, t_key_len);
rc = hv_store(hv, t_key, t_key_len, v, 0);
if (!rc) XSRETURN_UNDEF;
hv_delete(hv, f_key, f_key_len, 0);
will do the trick. The reference count of the v SV has to be incremented
because (for some idiotic reason) hv_delete mortalizes the SV it returns
to the caller (starting with perl 5.14, this is at least documented
Example Perl program
use MAD::xso_loader '/tmp/hm.xso';
$h = 'b';
hash_move(%h, 'b', 'a');
I realize this is less-than-useful but my so-called employer has some
claim to the infrastructure code used for compiling and linking
standalone .xs files and to the loader. Since the 'compile and link'
scripts are IMHO trivial, I posted them a while ago and the same posting
also contains a description how to load a shared object into perl via
Considering that linking C code into perl is not useful wrt 'getting
your name published on the WWW', this is something where CPAN will
let you squarely down (Inline:C might be usuable but that's a PITA and I
wouldn't ever want to use it myself).