I've been overworked for months. I'm on the road this week. I spoke at a user group meeting last night and spent nearly four hours driving back and forth just to get to the hotel late — and I overslept a bit.
These are probably not opportune times to be coding, but adding nicer directory listings to Jellybean, I wondered if there was a module to convert file sizes in raw bytes to nicer suffixed equivalents. Not finding anything called File::Size in the first ten pages of CPAN results, I threw together some tests and wrote my own:
sub describe_size { my $size = shift; return $size if $size < 1024; for my $unit (qw( k M G T P E )) { $size /= 1024; return int( $size ) . $unit if $size < 1024; } }
There's an elegance I like, but if it's not so useful, I won't package it for the CPAN. Opinions? (If you saw an earlier version that skipped terabytes and petabytes, I've already fixed that!)
LOL. I had the same problem 2 days ago, and of course ended up writing my own module, Format::FileSize, before realizing that Number::Format had a function that's suspiciously similar.
What's with everyone having that same idea this week?
Can't comment on whether it needs to be a module or not but that is some beautiful code.
It brought a smile to my face this cool and wet morning in Bristol.
You probably ought to change
qw( k M G T P E )
to
qw( Ki Mi Gi Ti Pi Ei )
when using
binary multiples.
You forgot something.. always idiot-proof
sub describe_size
{
my $size = shift;
# couldn't you just say return if $size < 1024 here?
return $size if $size < 1024;
for my $unit (qw( k M G T P E Z ))
{
$size/= 1024;
return int( $size ) . $unit if $size < 1024;
}
return int($size), "Y"; #need this for a fall-thru
}