Tie::Scalar::Random - fetch a randomly selected assigned value
use Tie::Scalar::Random; tie my $line, 'Tie::Scalar::Random'; while (<>) { $line = $_; } print $line; # a random line from STDIN die if $line ne $line; # should never die tie my $line, 'Tie::Scalar::Random', 1; while (<>) { $line = $_; } print $line; # a random line from STDIN print $line; # a possibly different random line from STDIN die if $line ne $line; # will probably die
Any time you fetch a value out of a scalar tied by Tie::Scalar::Random, it will produce a random value that was assigned to that scalar.
Tie::Scalar::Random
Note that it is both memory efficient and fair. Only one such value is stored at any given time. The scalar will also produce the same value until it is assigned to again, in which case it may or may not begin producing the new value.
It is essentially just the rand($.) < 1 idiom. See the Perl Cookbook, recipe 8.6, for an explanation.
rand($.) < 1
Note that if you pass a true value to tie, like so:
tie
tie my $line, 'Tie::Scalar::Random', 1;
Then every value assigned to the scalar will be remembered. This means it may use potentially a lot of memory. It also means every time the scalar is fetched, it can produce any of the values that were assigned to it since tie time (so $line eq $line may not hold true).
$line eq $line
Once the variable has been tied, it will produce undef (even if it had a genuine value before tie) until something is assigned to it.
undef
Shawn M Moore, sartak@gmail.com
sartak@gmail.com
Copyright 2007-2009 Shawn M Moore.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Tie::Scalar::Random, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Tie::Scalar::Random
CPAN shell
perl -MCPAN -e shell install Tie::Scalar::Random
For more information on module installation, please visit the detailed CPAN module installation guide.