#!/usr/bin/perl

$oneK = 1024; # 1 KB (kilo-byte)
$oneM = $oneK * $oneK; # 1 MB (mega-byte)
$oneG = $oneM * $oneK; # 1 GB (giga-byte)
$oneT = $oneG * $oneK; # 1 TB (tera-byte)
$oneP = $oneT * $oneK; # 1 PB (peta-byte)

print "1 K = $oneK B\n";
print "1 M = $oneM B\n";
print "1 G = $oneG B\n";
print "1 T = $oneT B\n";
print "1 P = $oneP B\n\n";

@list = ('B', 'K', 'M', 'G', 'T', 'P');

$invalid = 0; # initially set to false
while (!$invalid) 
{  
    print "X to exit or Write a positive integer with a space separated suffix of B, K, M, G, T or P: ";
   chomp($ans=<STDIN>);
   if (lc($ans) eq "x") {$invalid = 1; exit 1};
   ($num, $suffix) = split / /, $ans;
   $count = is_in($suffix);

   if (($count < 0) || ($count > $#list)) {$invalid = 1; exit 1};

   # Find the equivalent value in all lower units
   $cnum = $num;
   for ($i=$count; $i>=0; $i--)
   {   
       print "= $cnum $list[$i]\n";
       $cnum = $cnum * $oneK;
   };
   
   # Find the equivalent value in all higher units
   $cnum = $num;
   for ($j=$count+1; $j<= $#list; $j++)
   {
       $cnum = $cnum/$oneK;
       print "= $cnum $list[$j]\n";
   };
    print "\n";
};

sub is_in
{   
    my ($str) = @_;
    return (index "BKMGTP", $str);
}

