Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prompt for input and exit if the user entered an empty string?

Tags:

perl

I'm new to Perl and I'm writing a program where I want to force the user to enter a word. If the user enters an empty string then the program should exit.

This is what I have so far:

print "Enter a word to look up: ";

chomp ($usrword = <STDIN>);
like image 485
NewLearner Avatar asked Mar 12 '12 03:03

NewLearner


People also ask

How can I check if a user has entered a string?

Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work.

How to avoid empty input in Python?

You have to use a break statement if the user enters some value. Where the while loop will run and prompt the input message until some value is given by the user. The syntax for while input is not empty in Python.

How do you read an empty string?

Checking the empty string To check if a given string is empty or not, we can use the strlen() function in C. The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.


1 Answers

You're almost there.

print "Enter a word to look up: ";
my $userword = <STDIN>; # I moved chomp to a new line to make it more readable
chomp $userword; # Get rid of newline character at the end
exit 0 if ($userword eq ""); # If empty string, exit.
like image 56
DVK Avatar answered Nov 14 '22 04:11

DVK