I admit that dualvar was a term I never felt looking up until it came up recently here at the Monastery at Re^2: Rosetta Code: Long List is Long -- dualvar by marioroy. And I had a look at it. I found that Scalar::Util's dualvar can indeed create such a variable but I did not find any way of driving an existing variable into schizophrenic behaviour.
And so here is a gutty way to alter the string and/or numeric part of an existing scalar. Mind you I did a brief search on whether there was already some existing package doing that but did not find any.
This can find applications in some cases of the Schwartzian transform where the "decorations" and "undecorations" can apply on existing data rather than creating new (re: decorate/undecorate, Schwartzian_transform). The concept is not new (e.g. see comments under https://www.endpointdev.com/blog/2009/08/perls-scalarutildualvar/), but I did not find anything without creating new (dual)var but altering existing var. So here it is in a single-file SCSE form (XS can be found in ./_Inline/build dir):
## by: bliako ## on: 2022-12-05 ## EDIT: kudos to https://metacpan.org/release/PEVANS/Scalar-List-Util +s-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"; ;
Hacking away with Perl into the new year ... (actually I think I am in 2048 already, riding on Perl)
bw, bliako
In reply to Schizophrenic var by bliako
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |