SilverFox <[EMAIL PROTECTED]> wrote:

: 
: I haven't put anything together as yet. Putting
: some if/elsif statement together would be the
: easiest way I can think off. Something like:


    We can see a few problems right off. All scripts
should start with 'strict' and 'warnings'. We need a
consistent naming convention for variables. If some
start with capitalized letters, there should be a
non-arbitrary reason for doing so.

: $kilo= 1024;
: $Mega= 1048576;
: $gig= 1073741824;


use strict;
use warnings;

my $kilobyte = 1024;
my $megabyte = 1024 ** 2;
my $gigabyte = 1024 ** 3;

 
: print "Please enter your number:\n";
: chomp($num=<STDIN>);

chomp( my $value = <STDIN> );

: if ($num >= $gig)
: {
:         "need code to do the convertion/rounding
:         of given number" print "you entered:
:         $num\n"; print "which is:
: } elsif {
: continue with the same format........
: 
: }
: 
: The problem i'm having it converting/rounding the
: inputted number into a valid byte (KB/MB/GB) count.

    I suppose that takes some basic math. To round
to a whole number, we examine the fraction to
determine whether we should adjust the whole number
up or down. It is important to separate the number
from the fraction.

   Luckily, Math::Round has the nearest() function.
To find the nearest number of units, we use this.

nearest( $unit, $number ) / $unit


    Here's one solution. It's very generic. One
could easily adopt it for miles, yards, and feet
given a value in feet. I leave error checking to
you.


use strict;
use warnings;

use Math::Round 'nearest';

print "Please enter your number:\n";
chomp( my $value = <STDIN> );

my %units = (
    1024      => 'KB',
    1024 ** 2 => 'MB',
    1024 ** 3 => 'GB',
);

foreach my $unit ( sort {$b <=> $a} keys %units ) {
    if ( $value >= $unit ) {
        printf "%s => %s %s\n",
            $value,
            nearest( $unit, $value ) / $unit,
            $units{ $unit };
        last;
    }
}

__END__


    We still need to handle values smaller than
1024, but this solution might make that easier
to do. It won't handle non-positive values, though.


my %units = (
    1024 ** 0 => 'Bytes',
    1024 ** 1 => 'KB',
    1024 ** 2 => 'MB',
    1024 ** 3 => 'GB',
);


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
254 968-8328












-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to