sol4-17.pl
#!/usr/local/bin/perl
#
# $Id: sol4-17.pl,v 0.06 2024/11/10 20:07:46 kc4zvw Exp kc4zvw $
use 5.036_003;
use strict;
use warnings;
# ***====================================================================
# **
# ** Author: David Billsbrough <billsbrough@gmail.com>
# ** Created: Friday, April 05, 2024 at 08:58:05 (EDT)
# ** License: GNU General Public License - version 2
# ** Version: $Revision: 0.06 $
# ** Warranty: None
# **
# ** Purpose : demo - shuffle a numeric, string, and file array.
# **
# ***====================================================================
#####################
### Subroutines ###
#####################
# 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 @arr2 = qw(abc def ghi jkl mno pqr stu vw xyz);
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 about error while closing - '$path_to_file'.\n";
warn "Contining - $!\n";
}
print "\n";
# Assuming @array is your array:
print join(", ", @array);
print "\n";
fisher_yates_shuffle(\@array);
print join(", ", @array);
print "\n\n";
# Assuming @arr2 is your array:
print "@arr2";
print "\n";
fisher_yates_shuffle(\@arr2);
print "@arr2";
print "\n\n";
# Assuming @lines is your array:
print "@lines";
print "\n";
fisher_yates_shuffle(\@lines);
print "@lines";
print "\n\n";
# EOF