[Courses] [Perl] Part 3: User Input and "chomp"

Karine Delvare kproot at nerim.net
Thu Apr 21 01:57:47 EST 2005


Oops... saturday I told myself I should wait this time, and then I completely forgot about the course! sorry


On Fri, 15 Apr 2005 15:04:01 +0100
Dan <dan at cellectivity.com> wrote:

> LinuxChix Perl Course Part 3: User Input and "chomp"
> 
> 4) Exercises
> 
> a) Write a currency conversion program to convert between dollars and
> euros.

#!/usr/bin/perl -w
use strict;

print "Conversion from dollars to euros
Please enter an amount:\n";
my $dollars = <STDIN>;
chomp $dollars;

my $euros = $dollars * 0.76;
print "$dollars dollars are $euros euros\n";

> b) To make the previous exercise more interesting, have the program
> ask for the exchange rate.

For that exercise I tried to write the line: my $rate = chomp(<STDIN>);
because it was more "natural" for me than a function (chomp) being applied to a assignment. Which is very bad as you just told chomp does not return any value. Moreover, it cannot modify <STDIN>, I got that error: Can't modify <HANDLE> in chomp. Bad, bad me :)

#!/usr/bin/perl -w
use strict;

print "Conversion from dollars to euros
Please enter exchange rate:\n";
chomp(my $rate = <STDIN>);
print "Please enter an amount:\n";
chomp(my $dollars = <STDIN>);

my $euros = $dollars * $rate;
print "$dollars dollars are $euros euros\n";

> c) Try running the following program:
> 
>   #!/usr/bin/perl -w
>   use strict;
>   
>   local $/ = ",";
>   my $line = <STDIN>;
>   print "$line\n";
> 
> What happens when you run it?  Try entering a line without a comma
> followed by one with a comma. Can you explain what is happening?

When I enter a line without a comma, a new blank line seems to be waiting for more input. I then entered a line with a comma (like "hello, somebody here?"), and I got my first line printed, and the second one printed without anything after the comma.

Thoughts:
1- there is not any loop in this perl file, so it seems that $line contains my two lines.
2- the program stops asking from input as soon as it gets a coma. It does not even go any further than the coma.
3- that behaviour was observed before with the newline character

So it seems the comma has now replaced the newline character, but only for the "stop taking input" part (that is, I didn't see my first newline turn into a comma at the end of my first line).
By "default", that strange $/ variable must equal "\n", and must be what you called : line input separator.

> What effect does this have on the "chomp" function?

Adding chomp to the input line, I saw I got the same result, but cut just before the comma instead of just after. So chomp behaves well and removes the line input separator, which is not the newline in that case, but the comma.

> If you need help, try reading "perldoc perlvar":
> 
>   $ perldoc perlvar
> 
> and looking under "INPUT_RECORD_SEPARATOR"

Interesting reading :)

Karine


More information about the Courses mailing list