#! /usr/bin/perl -w # This file is maintained at http://git.mdcc.cx/draai # exec shuf : does the same, for input on stdin # Copyright: © 2001 Joost van Baal # This script is in the public domain. use strict; # # permutate - give a random permutation # # permutate 3 e.g. could return (0, 2, 1) # sub permutate { my $n = shift; my %h; for my $i (0 .. $n-1) { # rand $exp - a random fractional number >= 0, < $exp my $r = int rand $n - $i; my $k = -1; # find r-th undefined key in %h for my $j (0 .. $r) { # go find the next undefined key after number $k $k++; while (defined $h{$k}) { $k++; } } # and fill it with $i $h{$k} = $i; } return map { $h{$_} } (0 .. $n-1); } my @a; if (@ARGV) { @a = map { $ARGV[$_] } &permutate( scalar @ARGV ); print "@a\n"; } else { @a = <>; @a = map { $a[$_] } &permutate( scalar @a ); print @a; } __END__ =pod =head1 NAME dr_permutate - print randomly permutated arguments or stdin =head1 SYNOPSIS B I B =head1 DESCRIPTION When called with arguments, B returns its arguments in randomly permutated order, space separated. When called without any arguments, B expects a line-oriented file on stdin. It returns the contents of this file, with lines randomly permutated. =head1 EXAMPLE Running $ dr_permutate foo bar baz could return bar foo baz . Running $ cat < =cut