sol4-17.pl


#!/usr/local/bin/perl -w
#
# $Id: sol4-17.pl,v 0.05 2024/04/05 16:19:18 kc4zvw Exp kc4zvw $

use 5.036_003;
use strict;
use warnings;

# fisher_yates_shuffle( \@array ) : generate a random permutation
# of @array in place

sub fisher_yates_shuffle {
	my $array = shift;
	my $i;

	for ($i = @$array; --$i;) {
		my $j = int rand ($i + 1);
		next if $i == $j;
		@$array[$i, $j] = @$array[$j, $i];
	}
}


####################
### main program ###
####################

my @array = qw/ 1 2 3 4 5 6 7 8 9 10 11 12 /;
my $path_to_file = "alpha.txt";
my $handle;

unless (open $handle, "<:encoding(ascii)", $path_to_file) {
	print STDERR "Could not open file '$path_to_file': $!\n";
	# we return 'undefined', we could also 'die' or 'croak'
	die "No reason to continue : $!\n";
	#return undef
}

chomp(my @lines = <$handle>);

unless (close $handle) {
	# what does it mean if close yields an error and you are just reading?
	print STDERR "Don't care error while closing - '$path_to_file'.\n";
	warn "contining - $!\n";
} 

# assuming @array is your array:
print join(", ", @array);
print "\n";
fisher_yates_shuffle(\@array);
print join(", ", @array);
print "\n\n";

# assuming @a is your array:
my @a = qw(abc def ghi jkl mno pqr stu vw xyz);
print "@a";
print "\n";
fisher_yates_shuffle(\@a);
print "@a";
print "\n\n";

# assuming @lines is your array:
print "@lines";
print "\n";
fisher_yates_shuffle(\@lines);
print "@lines";
print "\n\n";

# EOF