• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 953
  • Last Modified:

Get text input in a perl script, if statements, looping

I have a perl script and I want to get text input from a user. I pseudo-coded what I want to do because I don't know any perl:

#!/usr/bin/perl
print "Hello World\n";

do
  (get text input here)
  if text = a then print "Monkey\n";
  if text = b then print "Donkey\n";
  if text = c then exit loop
loop
0
silentreproach
Asked:
silentreproach
  • 2
  • 2
  • 2
2 Solutions
 
derelict_debrisCommented:
#!/usr/bin/perl
print "Hello World\n";

my $input;
my $quit = 0;
while(!$quit) {
  $input = <STDIN>;
  print "Monkey\n" if $input eq 'a';
  print "Donkey\n" if $input eq 'b';
  $quit++ if $input eq 'c';
}

exit;

that should do it for you -- if you've got questions, just ask

HTH - derelict
0
 
Adam314Commented:
print "Hello World\n";
while(1) {
      $text=<STDIN>;
      chomp($text);
      print "Monkey\n" if $text eq 'a';
      print "Donkey\n" if $text eq 'b';
      last if $text eq 'c';
}
0
 
derelict_debrisCommented:
oops!

add this line:
chomp($input);

after $input = <STDIN>;

otherwise your $input will have a '\n' at the end.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
silentreproachAuthor Commented:
I hope the points split is okay with you guys; I'm not fully sure of the protocol for awarding points.

Derelict was first, but Adam's solution seemed simpler and is the one I'm using.  Both worked for me, thanks!
0
 
silentreproachAuthor Commented:
I am having one small issue, I'd like to print the value of $text after the chomp statement, but this syntax doesn't work:

print "Hello World\n";
while(1) {
      $text=<STDIN>;
      chomp($text);
>>>print $text;
      print "Monkey\n" if $text eq 'a';
      print "Donkey\n" if $text eq 'b';
      last if $text eq 'c';
}
0
 
Adam314Commented:
print $text will print the text, but there will be no newline after it is printed.
You might want this:
    print "$text\n";
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now