chomp($var = <>) Hitting enter directly ends the script...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ezechiel
    New Member
    • Jul 2009
    • 53

    chomp($var = <>) Hitting enter directly ends the script...

    Hi, while testing the program (runs in DOS), I thought "if someone hits enter without typing a letter before, what happens?"

    I tested and the script ends.. Is this normal, or how can I avoid this?

    [CODE=perl]print "To which analytical division is the study belonging to?\n\n";
    print "\ti: Immunology\n";
    print "\tc: Chemistry\n";
    print "\tq: Quit\n";
    print "\n\tYour choice: ";

    chomp (my $group = <>);
    my @group_list = ("i","c","q" );

    if (!(grep (/$group/i, @group_list))){
    do{
    print "\n\nYour choice is not valid.\nPlease enter a valid choice: (i/c/q)";
    print "\n\tYour choice: ";
    chomp ($group = <>);
    } until (grep (/$group/i, @group_list));
    }[/CODE]
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    What you want to do is to test to see if the variable, $var, has a value before moving on. Here is a quick script I wrote that does just that. And yes, it is tested to work.

    Code:
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $var;
    
    do{
        print("What is your text: ");
        chomp($var = <>);
    }until($var);
    
    print("$var \n");
    Hopefully that helps.

    Regards,

    Jeff

    Comment

    • ezechiel
      New Member
      • Jul 2009
      • 53

      #3
      Hey,

      thanks for the hint! It was not very nice to repeat "your choice" every time. So i had to find the solution to display "choice not valid" in case of just hitting enter. Tried some things and here is the solution:

      [CODE=perl]if (!$soft || !(grep (/$soft/i, @soft_list))) {
      do{
      print "\n\nYour choice is not valid.\nPlease enter a valid choice (a/h/x/e/w/n/q):\n";
      print "\n\tYour choice: ";
      chomp ($soft = <>);
      } until ($soft && (grep (/$soft/i, @soft_list)));
      }[/CODE]

      Comment

      • numberwhun
        Recognized Expert Moderator Specialist
        • May 2007
        • 3467

        #4
        I am glad that it worked for you. I figured you would have to modify it in some way to fit your code, but my point was to demonstrate that you needed to test for a value.

        Regards,

        Jeff

        Comment

        • ezechiel
          New Member
          • Jul 2009
          • 53

          #5
          :)

          well, you demonstrated efficiently :)
          thanks!

          Comment

          Working...