It is such a common situation when you need to place one or two
random banners, text chunks or links to a web page. Sometimes it
is wiser to get random values in perl code, but often I feel
extreme dearth of 'shuffle' virtual method - particularly when one
of our html coders asks me how to do it in TT.

Yes, I know about Template::Plugin::Shuffle by Tatsuhiko Miyagawa,
but it is rarely preinstalled on hosting servers and based on
another module, Algorithm::Numerical::Shuffle. And I usually feel
too lazy to go and install it myself (and our system administrator
is even more lazy).

So I suggest adding 'shuffle' to standard virtual methods. I have
made quite simple and small realization (independent of any
modules), and propose it to be included in TT 2.15.

Attached files contain test (to be placed in t/vmethods directory)
and patches to lib/Template/Stash.pm and vmethods documentation
source in src/Manual/VMethods.tt2 from separate 'docsrc' package
(I'm not sure in my English, so please read the docs carefully).

Here is it proposed vmethod:

    'shuffle'   => sub {
        my ($list, $limit) = @_;
        my @r = \( @$list ); # a list of refs to @$list items
        my $i = @$list;
        $limit = $i if $limit < 1 || $limit > $i;
        return [ map {
            my $n = int rand $i--;
            ( ${$r[$n]}, $r[$n] = $r[$i] )[0];
        } (1 .. $limit) ];
    },


-- 
Sergey Martynoff

Attachment: shuffle.t
Description: Binary data

Attachment: shuffle_docs.patch
Description: Binary data

Attachment: shuffle_vmethod.patch
Description: Binary data

Reply via email to