Tie-Pick

 view release on metacpan or  search on metacpan

lib/Tie/Pick.pm  view on Meta::CPAN

package Tie::Pick;

use 5.006;

use strict;
use warnings;
no  warnings 'syntax';

our $VERSION = '2009110701';


sub TIESCALAR {
    my $class  =   shift;
    do { require Carp;
         Carp::croak ("tie needs more arguments")
    } unless @_;
    bless [@_] => $class;
}

sub FETCH     {
    my $values = shift;
    return undef unless @$values;
    my $index  = int rand @$values;
    unless ($index == $#$values) {
        @{$values} [$index, $#$values] = @{$values} [$#$values, $index];
    }
    pop @$values;
}

sub STORE     {
    my $self = shift;
    do { require Carp;
         Carp::croak ("assignment needs reference to non empty array")
    } unless 1 == @_ && 'ARRAY' eq ref $_ [0] && @{$_ [0]};
      @$self = @{$_ [0]};
}


1;

__END__

=pod

=head1 NAME

Tie::Pick - Randomly pick (and remove) an element from a set.

=head1 SYNOPSIS

    use Tie::Pick;

    tie my $beatle => Tie::Pick => qw /Paul Ringo George John/;

    print "My favourite beatles are $beatle and $beatle.\n";
    # Prints: My favourite beatles are John and Ringo.

=head1 DESCRIPTION

C<Tie::Pick> lets you randomly pick an element from a set, and have
that element removed from the set.

The set to pick from is given as an list of extra parameters on tieing
the scalar. If the set is exhausted, the scalar will have the undefined
value. A new set to pick from can be given by assigning a reference to
an array of the values of the set to the scalar.

The algorithm used for picking values of the set is a variant of the
Fisher-Yates algorithm, as discussed in Knuth [3]. It was first published
by Fisher and Yates [2], and later by Durstenfeld [1]. The difference
is that we only perform one iteration on each look up.

If you want to pick elements from a set, without removing the element
after picking it, see the C<Tie::Select> module.

=head1 CAVEAT

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 1.871 second using v1.00-cache-2.02-grep-82fe00e-cpan-d29e8ade9f55 )