Perl Programming Page 3 - Scalars: Building a Currency Converter |
Let’s begin to wind up this chapter with a real example—a program to convert between currencies. This is our very first version, so we won’t make it do anything too clever. As we get more and more advanced, we’ll be able to hone and refine it. #!/usr/bin/perl -w use strict; my $yen = 105.6; # as of 02 February 2004 print "49518 Yen is ", (49_518/$yen), " dollars\n"; Save this, and run it through Perl. You should see something like this: $ perl currency1.pl First, we declare the exchange rate to be a lexical variable and set it to105.6. my $yen = 105.6; Notice that we can declare and assign a variable at the same time. Now we do some calculations based on that exchange rate: print "49518 Yen is ", (49_518/$yen), " dollars\n"; Of course, this is currently of limited use, because the exchange rate changes, and we might want to change some different amounts at times. To do either of these things, we need to be able to ask the user for additional data when we run the program. Introducing <STDIN> Perl reads from standard input (the keyboard) with<STDIN>. It reads up to and including the newline character, so the newline is part of the string read in. To read a single line of input from the user we can say something like print "Please enter something interesting\n"; This will read one line from the user, including the newline character, and assign the string that was read to the variable$comment. Let’s use this to get the exchange rate from the user when the program is run. This example will read the exchange rate from the user’s keyboard, storing it in$yen: #!/usr/bin/perl -w use strict; print "Currency converter\n\nPlease enter the exchange rate: "; print "49518 Yen is ", (49_518/$yen), " dollars\n"; Now when you run the program, you’ll be asked for the exchange rate. The currency values will be calculated using the rate you entered: $ perl currency2.pl Please enter the exchange rate: 100 Note that this time we read the exchange rate from the user’s keyboard and it was read in as a string. Perl converts the string to a number in order to perform the calculation. So far, we haven’t done any checking to make sure that the exchange rate given makes sense; this is something we’ll need to think about in the future.
blog comments powered by Disqus |
|
|
|
|
|
|
|