ritz303 has asked for the wisdom of the Perl Monks concerning the following question:

Wise and great monks, I know you'll put me on the right path to enlightenment. I'm sure I'm overlooking something simple. I have a text menu where you select an option by number. If you select an $answer >= 4 it loops just fine back to the menu options, but if the user just hits the "Enter" key it errors out. This line sort of works, if ( $answer >= 4 || $answer eq "" ), I still get a warning, but it does loop and print the menu again. Also, I've tried the following pieces of code in different parts of my code, but no success:

$answer =~ s/\s+$//g; $answer =~ tr/\015//d;

Below is my code:

#!/usr/bin/perl use strict; use warnings; use diagnostics; my $x = 0; my $answer; my %menu_selection = ( '1' => "Option 1....", '2' => "Option 2....", '3' => "Option 3...." ); sub menu () { print STDOUT <<EOF; Please select one of the following locations: 1.) Option 1.... 2.) Option 2.... 3.) Option 3.... EOF print "\nSelection: "; chomp( $answer = <STDIN> ); } while ( $x == 0 ) { &menu; if ( %menu_selection ) { if ( $answer >= 4 || $answer eq "" ) { print "The menu selection is: $answer\n"; print "\nWrong selection, please make a different selec +tion.\n\n"; $x = 0; } else { print "$menu_selection{$answer}\n"; $x = 1; } } }

Should I assign a string or numeric value to $answer before making any reference to it? I know there is the "Term::Menu" module (which may simplify things), but I don't want to install it on a 1200+ nodes. Just FYI, the script runs on Linux only. Thank you in advance for any help!

Replies are listed 'Best First'.
Re: Text Menu Not Looping on CR/LF
by JavaFan (Canon) on May 02, 2011 at 15:55 UTC
    Why not just check if the answer in in %menu_selection, and exit the loop only then? Something like:
    while (1) { print <<EOF; Please select one of the following locations: 1.) Option 1.... 2.) Option 2.... 3.) Option 3.... EOF print "Selection: "; chomp(my $answer = <>); if ($menu_selection{$answer}) { print $menu_selection{$answer}, "\n"; last; } }

      Thanks, JavaFan! That worked. It makes complete sense, now that I think about it. Sometimes, I make my code more complicated then it should be.

Re: Text Menu Not Looping on CR/LF
by choroba (Cardinal) on May 02, 2011 at 15:54 UTC
    I'd use
    if $answer and $answer >=4
    which can still give you some warnings if the user enters QWERTY or something similar. But why do not you use
    if not exists $menu_selection{$answer}