in reply to force user to only enter numbers
Above, you have several good answers to turn in (this is homework, isn't it? If so, better to label it so there's no question about your integrity) but your original code suggests you'll benefit from some of the pointers in the comments below:
#!/usr/bin/perl use strict; # strict and warnings are your friends. USE THEM AL +WAYS! use warnings; # 923876 my $num; input(); # you need not dump all your functions into subs # and certainly not into chained subs, but using ch +ained subs # here makes it easier for me to point out a few th +ings =head print "\n Press any key to exit"; # Utterly unnecessary - # your program will exit when it run +s out of $key = <STDIN>; # instructions, absent code to speci +fically do # otherwise ... such as sub quit_or_ +repeat: #End of Program =cut sub input { print "Enter an integer that is between 0 and 9: "; # no newline +so user can chomp ($num = <STDIN>); # enter data +at prompt test_input(); } sub test_input { if ( $num =~ /^[1-8]$/ ) { # 1...8 are the numbers "between 0 an +d 9" # as spec'ed by the prompt in OP's co +de main(); } else { print "Only single-digit, positive integers, 1 - 8, are allowe +d\n"; input(); } } sub main { for(my $i=1; $i<=$num; $i++) { print "$i "; } print "\n"; quit_or_repeat(); # sub called here actually does something # contrast w/ the original "$key = <STDIN> # # End of Program" + } sub quit_or_repeat { my $key = ''; print "\n Press 'q' to quit or any other key to continue: "; chomp ($key = <STDIN>); if ( lc($key) eq 'q' ) { # either 'q' or "Q" quits exit; } else { input(); # go another round } }
|
|---|