Shawn M Moore > Tie-Scalar-Random-0.02 > Tie::Scalar::Random

Download:
Tie-Scalar-Random-0.02.tar.gz

Dependencies

Annotate this POD

Website

CPAN RT

Open  0
View/Report Bugs
Module Version: 0.02   Source  

NAME ^

Tie::Scalar::Random - fetch a randomly selected assigned value

SYNOPSIS ^

    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

USAGE ^

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.

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.

Note that if you pass a true value to tie, like so:

    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).

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.

AUTHOR ^

Shawn M Moore, sartak@gmail.com

COPYRIGHT & LICENSE ^

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.

syntax highlighting: