HOME

The Perl 5 Project

Introduction

Add something here ...

Example Number One

Add something here ...



  

An example fisher_yates_shuffle in Perl

A test program from the O’Reilly® Perl Cookbook.

Formatted copy of program


#!/usr/bin/env perl
#
# $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";

# End of File

  

The output ...


1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
8, 12, 7, 11, 9, 4, 3, 10, 2, 1, 6, 5

abc def ghi jkl mno pqr stu vw xyz
stu abc mno pqr vw jkl ghi def xyz

alpha bravo charlie delta echo foxtrot golf hotel india
foxtrot echo hotel india bravo delta alpha golf charlie

  

Example Number Four : a Shellsort

The source code for sample003.pl


  

The output of the program : sample003.pl ...


  

Resources

How to get started learning the Perl Project ...

  1. A — (unkown) ...
  2. B — (unkown) ...
  3. C — (unkown) ...
  4. Links — (blank) ...

Miscellaneous

Add something here ...






Revised: Friday, April 05, 2024 at 11:47:42 AM (EDT)