Search code examples
perl

Getting a value expressed with the memory unit


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?


Solution

  • You could set up a hash like this:

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

    And then parse the text like this:

    if ( $current_value =~ /(\d+)(KB|MB|GB)/ ) {
        $current_value = $1 * $FACTORS{$2};
    }
    

    In your example the regex has a * which I'm not sure you intend, because * means "zero or more" and so (+\d)(MB)* would match 10 or 10MB or 10MBMB or 10MBMBMBMBMBMBMB.