From ebba23390b6db8e5e57df2d37dcdf171cd76aa94 Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Sat, 23 Mar 2024 22:27:51 +0800 Subject: [PATCH] maze: options before arguments (#516) * The usage string is the source of truth; optional maze algorithm flag goes before optional width and height arguments * Remove the grep that reconstructs ARGV with options removed; this allowed incorrect usage "perl maze 20 30 -sf" to be accepted --- bin/maze | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/bin/maze b/bin/maze index e2e73408..3ddae4e4 100755 --- a/bin/maze +++ b/bin/maze @@ -34,26 +34,20 @@ sub traverse_randomly { rand(@walk) } # fiendish mazez (random walks) sub traverse_randomly_deep {-rand(@walk/2) } # longer random walks sub traverse_randomly_shallow { rand(@walk/2) } # shorter random walks +my %alg = ( + '-fl' => \&traverse_by_breadth, + '-fi' => \&traverse_randomly, + '-df' => \&traverse_randomly_deep, + '-sf' => \&traverse_randomly_shallow, +); my $walk_function = \&traverse_by_depth; - -foreach my $switch (grep /^\-/, @ARGV) { - $walk_function = \&traverse_by_breadth if ($switch =~ /^-fl/i); - $walk_function = \&traverse_randomly if ($switch =~ /^-fi/i); - $walk_function = \&traverse_randomly_deep if ($switch =~ /^-df/i); - $walk_function = \&traverse_randomly_shallow if ($switch =~ /^-sf/i); - &usage if ($switch !~ /^-(fl|fi|df|sf)$/i); +while (@ARGV && $ARGV[0] =~ /^\-/) { + my $switch = shift; + $walk_function = $alg{$switch} or usage(); } - -@ARGV = grep !/^\-/, @ARGV; -&usage if (@ARGV && (@ARGV != 2)); - -# -## Parse maze size options. Fall back on standard behavior if the -## size isn't specified on the command line. - -my ($width, $height); - -($width, $height) = @ARGV if (@ARGV == 2); +my $width = shift; +my $height = shift; +usage() if @ARGV; sub get_number { my ($prompt, $value) = @_;