Re: RFC on ${^RNG} callback API for overriding rand()

[email protected] (Michael Conrad)
Newsgroups perl.perl5.porters
Message-ID <[email protected]>
On 8/17/26 09:34, demerphq wrote:
> Add support for an ${^RNG} hook

The ^RNG variable makes sense to me, though adding a perl method call to 
every invocation of rand() seems less than ideal.

> At the same time we dont really want to change Perls internal code to
> use something other than drand48(). There is lots of code that expects
> that doing srand(1234) will produce test results that look a specific way
>
Perhaps, but that pattern already experienced breakage with 5.20 and in 
tests it's not *that* much extra hassle to globally define a custom 
CORE::rand, which is the better way to future-proof the tests anyway.  
It's basically the same problem that modules like Test::Mock::Time solve.

It might be nice if the rand implementation was selected lexically as a 
feature, so `use feature "rand_pcg";` could give you values from an 
internal PCG-XSH-RR by rand() calls in that scope, and would not affect 
rand() calls outside that scope.  Then it becomes a default in `use 
v5.48;` or something.  That preserves the srand()-in-tests behavior.  
...unless they depend on the behavior of a module that changes to use 
this feature, but that was a potential breakage inherent in the choice 
to depend on srand() in the first place.

If the ${^RAND} variable doesn't add too much overhead, that could be 
added in addition to the feature flag, and override rand() regardless of 
feature flag.


> I chose to make RNG use a UV as its base currency, so rand() calls
> ${^RNG}->rand_uv() which returns a UV, which is then converted into
> whatever the user requested. I did it this way so that any floating
> point operations or conversion to floating point operations could be
> performed by the C code. It feels like a more flexible foundation
> than using a float.

Randomizing a string of bytes could also be a good base 
currency.  Regardless of which it uses, it seems like a good idea to 
have a "RNG object" specification that people can standardize around.

-Mike C
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.