By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,903 Members | 1,067 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,903 IT Pros & Developers. It's quick & easy.

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

P: 53
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?

Expand|Select|Wrap|Line Numbers
  1. print "To which analytical division is the study belonging to?\n\n";
  2. print "\ti: Immunology\n";
  3. print "\tc: Chemistry\n";
  4. print "\tq: Quit\n";
  5. print "\n\tYour choice: ";
  6.  
  7. chomp (my $group = <>);
  8. my @group_list = ("i","c","q");
  9.  
  10. if (!(grep (/$group/i, @group_list))){
  11.        do{
  12.                print "\n\nYour choice is not valid.\nPlease enter a valid choice: (i/c/q)";
  13.                print "\n\tYour choice: ";
  14.                chomp ($group = <>);
  15.         } until (grep (/$group/i, @group_list));
  16. }
Dec 1 '09 #1
Share this Question
Share on Google+
4 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
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.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my $var;
  7.  
  8. do{
  9.     print("What is your text: ");
  10.     chomp($var = <>);
  11. }until($var);
  12.  
  13. print("$var \n");
  14.  
Hopefully that helps.

Regards,

Jeff
Dec 1 '09 #2

P: 53
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:

Expand|Select|Wrap|Line Numbers
  1. if (!$soft || !(grep (/$soft/i, @soft_list))) {
  2.     do{
  3.           print "\n\nYour choice is not valid.\nPlease enter a valid choice (a/h/x/e/w/n/q):\n";
  4.           print "\n\tYour choice: ";
  5.           chomp ($soft = <>);
  6.     } until ($soft && (grep (/$soft/i, @soft_list)));
  7. }
Dec 2 '09 #3

numberwhun
Expert Mod 2.5K+
P: 3,503
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
Dec 2 '09 #4

P: 53
:)

well, you demonstrated efficiently :)
thanks!
Dec 3 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.