Log in

View Full Version : Need help with Perl!


dragonfly11
Jul 25, 2005, 05:19 PM
I am currently learning how to use Perl from a book. One of the exercises on chapter 4 (Scalars, Arrays and Hashes) has really left me dumb. This is the problem, but I can't figure out the coding to make the "Course code" typed in the user to appear in the place of "Shell Programming" where it should be.

HELP!

Exercise:

Write a script called elective that will contain a hash.
a. The keys will be code numbers --2CPR2B, 1UNX1B, 3SH414, 4PL400.
b. The values will be course names, C Language, Intro to UNIX, Shell Programming, Perl Programming.
c. PRint the entire array.
d. Ask the user to type the code number for the course he plans to take this semester and print a line resembling the following:

You will be taking Shell Programming this semester.

Here is the coding I have so far:

#! Usr/bin/perl


%courses = (
'2CPR2B' => 'C Programming',
'1UNX1B' => 'Intro to UNIX',
'4PL400' => 'Perl Programming',
'3SH414' => 'Shell Programming',
);
print %courses, "\n";
print "Please type in the code number of the course you will be taking this semester:", "\n";
$course=<STDIN>;
print "You will be taking $courses{$course} this semester.\n";

LTheobald
Jul 26, 2005, 03:34 AM
Try adding the following after the line "$course=<STDIN>;"

chop($course);
This will remove any new lines characters from the end of the $course variable which is what could be causing the mismatch. Let me know if this works. I've never tried Perl before but I'll try and help some more.

dragonfly11
Jul 26, 2005, 06:56 AM
YES!! Thank you so much my friend! It worked like a charm!

Now I can keep going further in my exercises...

Thanks again! :)
dragonfly11

iFire
Nov 17, 2008, 12:14 PM
Truth be told, when you want to remove the newline character which is always implemented to the end of STDIN, you should use chomp, which only removes the newline char. Chop removes the last char, whatever it maybe.

And you should do it like:
chomp($var = <STDIN>); #It saves a line. :D