[Edit][Create New]
[ IndexPage / ネットとプログラミング / CGI / 便利なスクリプト片(未整理) / random.pl ]

random.pl

package random;

sub pick_from_arrey{
	local(@arrey) = @_;
	&srand_once;
	$arrey[rand @array];
}

sub pick_from_file{
	local(*FILE) = @_;
	local($it, $., $_);
	rand($.) < 1 && ($it = $_) while <FILE>;
	return $it;
}

sub shuffle_file{
	local(*FILE) = @_;
	local(@new) = ();

	&srand_once;

	while(<FILE>){
		my $r = rand @new+1;
		push(@new,$new[$r]);
		$new[$r] = $_;
	}
	return @new;
}

sub shuffle_array{
	local(@old) = @_;
	local(@new) = ();

	&srand_once;

	for( @old ){
		my $r = rand @new+1;
		push(@new,$new[$r]);
		$new[$r] = $_;
	}
}

# 最初の一回だけsrandをかける

sub srand_once{
	srand $$|time if $srand;
	$srand = 1;
}