I think that produces the sort of result you were looking for (I adopted the mathematical corrections provided by DigitalKitty).#!/usr/bin/perl # (of course, "/usr/local/bin/perl" should work as well) use strict; if ( @ARGV != 3 ) { die "Usage: $0 starting_unit target_unit numeric_amount\n"; } my ( $from, $to, $value ) = @ARGV; #use these as exponents; below we just subtract exponents to get the a +nswer my %prefixes = ( "mega" => 6, "kilo" => 3, "milli" => -3, "micro" => -6, "nano" => -9, "pico" => -12, "femto" => -15, "atto" => -18, "zepto" => -21, "yocto" => -24, ); for ( $from, $to ) { next if ( exists( $prefixes{$_} )); my $msg = "$_ is not a known unit. Try one of these:\n"; for my $prf (sort { $prefixes{$b}<=>$prefixes{$a} } keys %prefixes + ) { $msg .= "\t$prf\n"; } die $msg; } my $exp = $prefixes{$from} - $prefixes{$to}; print "$value $from is ", $value * 10 ** $exp, " $to.\n";
The virtues and bonuses of using @ARGV to get user input from args on the command line are numerous, and you will appreciate them more and more as time goes by.
Simple example: does your shell support "command history", where you are able to use the "up-arrow" key to get back to a previous command, edit it and run again? (All decent shells have this.) Consider wanting to run your script 5 times with different user inputs... what is easier: answering the same three questions repeatedly 5 times? or recalling a previous command, changing one or more args on the command line, and running it again? Try it both ways, and see which one you like better.
In reply to Re: syntax error at labmonkey.pl line 1, at EOF
by graff
in thread syntax error at labmonkey.pl line 1, at EOF
by theredqueentheory
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |