#!/usr/bin/perl -w
use strict;
use Scalar::Util qw(looks_like_number); # this is a real pain otherwise..
# Extremely dumb, but I've wanted one for years.  I agonized over whether 
# (and how to) make a GUI that would just let you type in all but one value, 
# and then it would supply the unknown. I'll get that round-tuit someday.
# Till then, there's this.  Just tell it which is the unknown first, it'll 
# ask for the rest and give an answer - including your inputs (validation).

#********************************* variables *********************************
my ($E,$I,$R,$unk); # the obvious variables we need, global due to my lazy
#*************************************** subroutine(s) ***********************
# Sub to ask user for and return a numeric value - pass in the "name" 
# of what you want to ask for.
# Keeps asking till you put in some sort of valid numeric
sub getVal($)
{
 do 
 {
  print "Input the $_[0] ->"; #Trick, kinda. saves a line and a variable 
 } until looks_like_number($_ = <>); # Seems to be a good test
 chomp; # Remove newline...causes issues later
 return $_;
}
############################ main ############################################
print "Ohm's law calculator - E = IR \nGive us which you want to calculate, 
we'll ask for the rest and do it.\n";
do {
 print "\nWhat's the unknown?  E,I,R? (E) ->";
 $unk = lc (<>); # Make input case-insensitive
} until $unk =~ m/e|i|r/; # Try till valid unknown type

# OK, now compute the unknown, after asking for the knowns
$E = getVal("Volts")	unless $unk =~ m/e/i;
$I = getVal("Amps")	unless $unk =~ m/i/i;
$R = getVal("Ohms")	unless $unk =~ m/r/i;

# Older perls have no switch statement, so this'll do here
if ($unk =~ /e/) {$E = $I * $R;} # the most basic version
elsif ($unk =~ /i/) {$I = $E/$R;} # compute amps from volts and ohms
elsif ($unk =~ /r/) {$R = $E/$I;} # compute current from volts and resistance
print "Answer: Volts = $E, Amps = $I, Ohms = $R\n"; # we're done
##############################################################################
