Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why won't this code work?
#1
Below is my code, basically if the answer is "Y" then the script runs a message if it's something else then it closes.

Quote:#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Reply
#2
Try this:
Code:
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;

if ($answer eq "Y\n") {
    print "COOOL\n";
} elsif ($answer eq "N\n") {
    exit;
} else {
    print "I did not understand your response\n";
    exit;
}

This is just a simple example of how you would use <STDIN>, which is what you're using. <> is just a short version of standard input.

Actually a better setup would be something like this:
Code:
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;

if ($answer =~/Y/i) {
    print "COOOL\n";
} elsif ($answer =~/N/i) {
    exit;
} else {
    print "I did not understand your response\n";
        exit;
}

I forgot about case handling. This script will make the response case insensitive, so an input that is "n" instead of "N" will be the same thing. Same thing with "y" and "Y". Otherwise an input that it doesn't recognize will exit as well.

Essentially, this new code is the same as:
Code:
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;

if ($answer eq "Y\n" || $answer eq "y\n") {
    print "COOOL\n";
} elsif ($answer eq "N\n" || $answer eq "n\n") {
    exit;
} else {
    print "I did not understand your response\n";
        exit;
}

It's just that the other way is a little shorter. /i is used to define the value as case insensitive. Which is why it's the same thing as using the or definer "||" like above.

Reason your initial code didn't work is because you didn't define the input with the newline input \n. You also don't need to use "system exit;" you can just use "exit;" in the script to exit the script from being interpreted.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)