Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: pretty print bytes

by grinder (Bishop)
on Mar 28, 2002 at 14:33 UTC ( [id://154979]=note: print w/replies, xml ) Need Help??


in reply to pretty print bytes

That's pretty nice, although it does have a few problems. I wrapped it in a harness and checked a few boundary values:

-1 -> <1K 0 -> 1 -> <1K 10 -> <1K 100 -> <1K 511 -> <1K 512 -> 1K 513 -> 1K 999 -> 1K 1000 -> 1K 1023 -> 1K 1024 -> 1K 1025 -> 1K 10000 -> 10K 100000 -> 98K 1000000 -> 977K 10000000 -> 9766K 100000000 -> 95M 1000000000 -> 954M 10000000000 -> 9537M 100000000000 -> 93G 1000000000000 -> 931G 10000000000000 -> 9313G 100000000000000 -> 93132G 1000000000000000 -> 931323G

-1 gives an odd (arguable?) result, 0 gives nothing, and anything from 512 to 1023 is 1K, rather than <1K.

Suppose I want to extend it to teras and petas... and beyond? Can you see the redundancy in your code? How could you factor that out? If you did, it would be easier to extend.

BTW, my harness looks like this (ugly, but it gets the job done).

for my $amount( qw/-1 0 1 10 100 511 512 513 999 1000 1023 1024 1025 10000 100000 1000000 10000000 100000000 1000000000 10000000000 100000000000 1000000000000 10000000000000 100000000000000 1000000000000000/ ) { print "$amount -> ", amount($amount), "\n"; }

Ok, enough blabbering, here's how I would do it. Note that my routine produces different output. I think that is due to the way you employ 512 in your algorithm. I don't think that's necessary, but I'm not paying close attention.

sub amount { my $num = shift; return '' if $num < 0; return '0K' if $num == 0; return '<1K' if $num < 1024; my @suffix = qw/K M G T P/; my $offset = -1; while( $num >= 1024 and $offset < scalar @suffix ) { ++$offset; $num = int( $num / 1024 ); } return "$num$suffix[$offset]"; }

Extending this routing is as simple as increasing the @suffix array, which is as it should be. Note to readers: this routine, like the original both run cleanly under strict and warnings.


If you're curious, after peta comes exa (E), zetta (Z) and yotta(Y). Man, think of all the mp3s you could store on a yottabyte, of course, the backups would kill you. Just don't get me started on kibibytes and mebibytes.


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://154979]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-25 07:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found