Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a value expressed with the memory unit

Tags:

perl

I'm searching for a way to reduce the following piece of code to a single regexp statement:

if( $current_value =~ /(\d+)(MB)*/ ){
        $current_value = $1 * 1024 * 1024;
    }
    elsif( $current_value =~ /(\d+)(GB)*/ ){
        $current_value = $1 * 1024 * 1024 * 1024;
    }
    elsif( $current_value =~ /(\d+)(KB)*/ ){
        $current_value = $1 * 1024;
    }

The code performs an evaluation of the value that can be expressed as a single number (bytes), a number and KB (kilobytes), with megabytes (MB) and so on. How do I reduce the block of code?

like image 383
fluca1978 Avatar asked Jan 27 '26 12:01

fluca1978


1 Answers

Number::Format

use warnings;
use strict;

use Number::Format qw(format_bytes);
print format_bytes(1024), "\n";
print format_bytes(2535116549), "\n";

Output:

    1K
    2.36G
like image 191
toolic Avatar answered Jan 29 '26 02:01

toolic