A Stupid Little Module?

chromatic on 2003-08-29T01:51:55

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!)


Another module doing this...

lachoy on 2003-08-29T03:44:34

FWIW, Number::Format has a 'format_bytes' method that does this too.

Convert::SciEng

colink on 2003-08-29T04:44:13

Convert::SciEng 0.91 ,which I just uploaded to PAUSE, will do this. The previous versions only handled SI prefixes based on powers of 10 and a modified version supported by the circuit simulator SPICE.

Tu Quoque?

mir on 2003-08-29T06:16:52

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?

Elegant

gtod on 2003-08-29T08:40:46

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.

Of course you mean tebibytes and pebibytes...

brianiac on 2003-08-29T17:17:15

You probably ought to change qw( k M G T P E ) to qw( Ki Mi Gi Ti Pi Ei ) when using binary multiples.

whups!

WebDragon on 2003-08-29T17:28:34

You forgot something.. always idiot-proof :) and also Zettabytes and Yottabytes :)

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
}

Opportunity

pudge on 2003-09-02T23:47:34

I often do my best coding at inoppportune times. I don't know why that is. I got a hell of a lot done on Mac::Carbon and Mac::Glue while on vacation in WA last March.