## by: bliako ## on: 2022-12-05 ## EDIT: kudos to https://metacpan.org/release/PEVANS/Scalar-List-Utils-1.63/source/ListUtil.xs (line 1674, dualvar) use strict; use warnings; use Devel::Peek; use Inline Config => clean_after_build => 0; use Inline C => <<'EOC'; // alter the 'numeric' slot of existing var 'asv' with that of 'theiv' void setIV(SV *asv, SV *theiv){ (void)SvUPGRADE(asv, SVt_PVNV); SvIV_set(asv, SvIV(theiv)); SvIOK_on(asv); } // alter the 'string' slot of existing var 'asv' with that of 'thesv' void setSV(SV *asv, SV *thesv){ sv_setsv(asv, thesv); } EOC my $num = 42; my $x = "My name is Ace!"; Dump($x); setIV($x, $num); Dump($x); setSV($x, "Hello Ozy!"); Dump($x); # and here is a one-legged Schwartzian transform # to sort strings on their lengths using above XS: my @unsorted = ("Just", "another", "Perl\x{7}\x{7}\x{7}", "hacker\x{7}"); my @sorted = sort { $a <=> $b } map { setIV($_, length($_)); $_ } @unsorted; print "Sorted: @sorted\n"; ;