in reply to while loop almost correct

Hashes are good for this sort of work, the question number is the hash key and the answer is the hash value related to that key, read this intro as well, there are many ways to declare a hash, here I assigned an array to a hash...the program uses a label called "CHECK" to control its flow...If the letter choice corresponds to a key in the hash then that hash value would be defined and you would see the answer, else the program would go back to the label "CHECK:" and prompt you to answer the question once again..
use strict; use warnings; my @array = qw(a Grant b Yoda c Liberace d None); my %hash= @array; CHECK: print "Who's Buried in Grant's Tomb\n"; print <<ENDING; a. Grant b. Yoda c. Liberace d. None of the above. ENDING while(chomp(my $answer = <STDIN>)){ if(defined $hash{$answer}){ print "your Answer is \"$hash{$answer}\".\n"; print "Thank You.\n"; #do anything with the Answer.... exit; }else{ print "Please Pick a letter between A - D\n"; goto CHECK; } }


Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.

Replies are listed 'Best First'.
Re^2: while loop almost correct
by JadeNB (Chaplain) on Nov 17, 2009 at 20:38 UTC
    Hashes are good for this sort of work, the question number is the hash key and the answer is the hash value related to that key
    Any time you find yourself thinking of using a number as a key into a hash, you should probably think about whether you mean to be using an array instead. In this case (but not every case: a sparse array is better implemented as a hash, if I'm not mistaken), I think that the answer would be ‘yes’.
Re^2: while loop almost correct
by irvson (Sexton) on Nov 17, 2009 at 23:28 UTC

    Nice! Whole different approach. I've gotten far enough in my Perl "studies" (learning on my own; lots of programming experience with other languages) to know what a hash is. Never would have occurred to me to use it here. Thanks.

Re^2: while loop almost correct
by irvson (Sexton) on Nov 18, 2009 at 16:25 UTC

    I'd like to pursue this suggestion. I guess what prompts me most is the "goto." I remember from my days in learning BASIC (couple of decades ago) that "goto" could be handy or deadly -- depending on how it was used. What topic do I pursue in order to learn more about the "CHECK" and "ENDING" code?