print "I will calculate whatever\n", "you specify according to\n", "Ohm's law. What shall I\n", "calculate? Type either\n", "voltage, current, or\n", "resistance.\n"; my $i = 0; .... #### #!/usr/bin/perl -w use strict; my $line; while( (print "parameter to calculate?:"), ($line=), $line !~ /^\s*q(uit)?\s*$/i) { next if $line =~ /^\s*$/; #blank line => simple re-prompt if ($line =~ /^\s*(resistance|R)\s*$/i) { print "sub to calculate resistance\n"; } elsif ($line =~ /^\s*(voltage|V)\s*$/i) { print "sub to calculate voltage\n"; } elsif ($line =~ /^\s*(current|I)\s*$/i) { print "sub to calculate current\n"; } else { print "illegal entry!\n"; } } #### #!/usr/bin/perl -w use strict; my @tests = ('50 ma', '10ma', '2.3', '-.2 ma', '3.', '4.0', '10ba'); foreach my $input (@tests) { my ($amps, $flag_ma)= $input=~ /^\s*([-+]?\d*\.?\d+)\s*(ma|mA)?\s*$/; $amps /=1000 if defined $flag_ma; if (defined $amps) { print "$amps amps\n"; } else { print "$input is an illegal entry\n"; } } __END__ 0.05 amps 0.01 amps 2.3 amps -0.0002 amps 3. is an illegal entry 4.0 amps 10ba is an illegal entry #### prompt> i = 2.3 prompt> t=3 illegal syntax try again! prompt> r = 3 prompt> v? v=i*r i=2.3 r=3 v=6.9 prompt>v=9 prompt>i? i=v/r r=3 v=9 i=3 prompt>q good bye! #### #!/usr/bin/perl -w use strict; my %ohmsLaw; #i,v,r print "This is an Ohm's law program (V=I*R).\n", "enter statements like: \n", " Enter I,V,R equation> i=2.3 or 3.2 mA or 3.2 ma\n", " Enter I,V,R equation> R=4\n", " Enter I,V,R equation> v=? **asks for v to be printed**\n", " prints: v=9.2 ** 9.2= (2.3 x 4) **\n", "basically I calculate the value that you ask for\n", " based upon the previous entries for the other two\n", " variables\n", "enter q|Q|quit to quit program\n"; my $line; while( (print "Enter I,V,R equation>"), ($line=), $line !~ /^\s*q(uit)?\s*$/i) { next if $line =~ /^\s*$/; # simple re-prompt on blank line # # set an I,V,R variable... # if (my ($vir_letter, $number, $flag_ma) = $line =~ /^\s*([ivrIVR])\s*\=\s*([-+]?\d*\.?\d+)\s*(ma|mA)?\s*$/) { if ($vir_letter =~ /I/i) { $ohmsLaw{i} = $number; $ohmsLaw{i} /= 1000 if defined $flag_ma; } $ohmsLaw{v}=$number if $vir_letter =~ /V/i; $ohmsLaw{r}=$number if $vir_letter =~ /R/i; } # # output a calculated I,V,R value # elsif (my ($printValue) = $line =~ /\s*(i|v|r)\s*\=\s*\?\s*$/i) { foreach my $ltr (grep{$_ ne $printValue} keys %ohmsLaw) { print " $ltr=$ohmsLaw{$ltr}\n"; #list other values! } print "v=",$ohmsLaw{v}=$ohmsLaw{i}*$ohmsLaw{r},"\n" if $printValue =~ /V/i; print "i=",$ohmsLaw{i}=$ohmsLaw{v}/$ohmsLaw{r},"\n" if $printValue =~ /I/i; print "r=",$ohmsLaw{r}=$ohmsLaw{v}/$ohmsLaw{i},"\n" if $printValue =~ /R/i; } else { print "illegal syntax!\n"; } }