- perl way of getting a value expressed with the memory unit
- 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;
- }
- my %FACTORS = ( 'KB' => 1024, 'MB' => 1024**2, 'GB' => 1024**3 );
- if ( $current_value =~ /(d+)(KB|MB|GB)/ ) {
- $current_value = $1 * $FACTORS{$2};
- }
- use warnings;
- use strict;
- use Number::Format qw(format_bytes);
- print format_bytes(1024), "n";
- print format_bytes(2535116549), "n";
- __END__
- 1K
- 2.36G
- my $r;
- $current_value =~ s/
- (d+)(?:
- Ki (?{ $r = $^N * 1024 })
- | Mi (?{ $r = $^N * 1024 * 1024 })
- | Gi (?{ $r = $^N * 1024 * 1024 * 1024 })
- )/$r/xso;
- use Test::More;
- plan tests => 4;
- ##
- # Convert a string denoting '50MB' into an amount in bytes.
- my %FACTORS = ( 'KB' => 1024, 'MB' => 1024*1024, 'GB' => 1024*1024*1024 );
- sub string_to_bytes {
- my $current_value = shift;
- if ( $current_value =~ /(d+)(KB|MB|GB)/ ) {
- $current_value = $1 * $FACTORS{$2};
- }
- return $current_value;
- }
- my $tests = {
- '50' => 50,
- '52KB' => 52*1024,
- '55MB' => 55*1024*1024,
- '57GB' => 57*1024*1024*1024
- };
- foreach(keys %$tests) {
- is( string_to_bytes($_),$tests->{$_},
- "Testing if $_ becomes $tests->{$_}");
- }
- $ perl testz.pl
- 1..4
- ok 1 - Testing if 55MB becomes 57671680
- ok 2 - Testing if 50 becomes 50
- ok 3 - Testing if 52KB becomes 53248
- ok 4 - Testing if 57GB becomes 61203283968
- use strict;
- use warnings;
- use Regexp::Common;
- my %multiplier;
- my $multiplier_match;
- {
- # populate %multiplier
- my %exponent = (
- K => 1, # Kilo Kibi
- M => 2, # Mega Mebi
- G => 3, # Giga Gibi
- T => 4, # Tera Tebi
- P => 5, # Peta Pebi
- E => 6, # Exa Exbi
- Z => 7, # Zetta Zebi
- Y => 8, # Yotta Yobi
- );
- while( my ($str,$exp) = each %exponent ){
- @multiplier{ $str, "${str}B" } = (1000 ** $exp) x2; # K KB
- @multiplier{ "${str}i", "${str}iB" } = (1024 ** $exp) x2; # Ki KiB
- }
- # %multiplier now holds 32 pairs (8*4)
- # build $multiplier_match
- local $" #" # fix broken highlighting
- = '|';
- my @keys = keys %multiplier;
- $multiplier_match = qr(@keys);
- }
- sub remove_multiplier{
- die unless @_ == 1;
- local ($_) = @_;
- # s/^($RE{num}{real})($multiplier_match)$/ $1 * $multiplier{$2} /e;
- if( /^($RE{num}{real})($multiplier_match)$/ ){
- return $1 * $multiplier{$2};
- }
- return $_;
- }
- # @multiplier{ $str, "${str}B" } = (1000 ** $exp) x2; # K KB
- @multiplier{ $str, "${str}B" } = (1024 ** $exp) x2; # K KB