On Thu, 30 Jan 2003 21:58:10 +0300, Eri Mendz wrote: > Have here a temperature conversion program im trying to "perfect" but no > chance, its not working right. The input validation portion is fine, im > satisfied likewise with the conversion to celsius. My problem is > conversion to fahrenheit: the answer is not right so is the temp unit > during printout. The problem must be obvious but i pick-up slow. Can > you help me out and guide me :-) > > #!/usr/bin/perl -w > use strict; > > print "This is a temperature conversion program.\n"; > print "Enter temperature to convert(e.g., 100C, 212F): "; > chomp(my $input = <STDIN>); > if ($input =~ m/^([+-]?\d+)(\.{1}\d+)?[ ]?([cCfF])$/){ #validate input format ^^^^^ ^^^^ \.{1} is only a complicated way to express \. [ ]? is also complicated for a simple blank followded by a ?
> my $real_num = $1; $1 is the part before the \., $2 is the fraction part, so the line should be better my $real_num = $1.$2; Or perhaps it's better to rewrite the regexp to if (my ($val, $unit) = $input =~ /^([+-]?\d+(?:\.\d+)?) ?([cf])$/i) { ... } > my $temp_unit = $3; > my ($in_c, $in_f) = ($real_num, $real_num); > if ($temp_unit eq 'C' or 'c'){ > $in_f = ($real_num * 9 / 5) + 32; > printf "%.2f C is %.2f F\n", $real_num, $in_f; > } else { #it must be F if not C > $in_c = ($real_num - 32) * 5 / 9; > printf "%.2f C is %.2f F\n", $real_num, $in_c; > } > } else { > #input failed validation check > print "Error is detected in input\n"; > print "input format is number, optional space then letter C or F, case > insensitive, in exact order\n"; > print "Please check your input and try again.\n"; > } > Staring at the code trying to debug i realize is no nice exercise. > But i want to learn, so no excuse. TIA. BTW, there's also a CPAN module doing unit conversions stuff for you. Here's an example converting 72° Fahrenheit to Celsius. use Math::Units qw/convert/; print convert(72.0, 'F' => 'C'); Greetings, Janek -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]