Convert memory size (readable) to actual number (bytes) in Perl

Is there an actual package in CPAN for converting such a string:

my $string = "54.4M"
my $string2 = "3.2G"

in actual number in bytes:

54,400,000
3,200,000,000

And vice versa.

Basically, what I want to do at the end is to summarize the entire amount of memory.

+3
source share
4 answers

To get the exact output, use Number :: FormatEng and Number :: Format :

use strict;
use warnings;

use Number::FormatEng qw(:all);
use Number::Format qw(:subs);

my $string = "54.4M" ;
my $string2 = "3.2G" ;

print format_number(unformat_pref($string))  , "\n";
print format_number(unformat_pref($string2)) , "\n";

__END__
54,400,000
3,200,000,000             

By the way, it unformat_prefis only required if you are going to perform calculations with the result.

Number:: FormatEng ( ), . , k.

Number:: Format ( , ).

use Number::Format qw(:subs);

my $string = "54.4M" ;
my $string2 = "3.2G" ;

print round(unformat_number($string) , 0), "\n";
print round(unformat_number($string2), 0), "\n";

__END__
57042534
3435973837

, "", , Number::Format 1K 1024 , 1000 . , ( ), .

+5

CPAN, :

sub convert_human_size {
    my $size = shift;
    my @suffixes = ('', qw(k m g));
    for my $index (0..$#suffixes) {
        my $suffix = $suffixes[$index];
        if ( $size =~ /^([\d.]+)$suffix\z/i ) {
            return int($1 * (1024 ** $index));
        }
    }
    # No match
    die "Didn't understand human-readable file size '$size'";  # or croak
}

Number::Format format_number , (, "5,124" "5124" )

CPAN :

Number::Bytes::Human

:

  use Number::Bytes::Human qw(format_bytes);
  $size = format_bytes(54_400_000);

bs => 1000, 1000 1024.

+4

, , , , - :

#!/usr/bin/perl

use strict; use warnings;
my $base = 1000;

my %units = (
    K => $base,
    M => $base ** 2,
    G => $base ** 3,
    # etc
);

my @strings = qw( 54.4M 3.2G 1K 0.1M .);
my $pattern = join('|', sort keys %units);

my $total;

for my $string ( @strings ) {
    while ( $string =~ /(([0-9]*(?:\.[0-9]+)?)($pattern))/g ) {
        my $number = $2 * $units{$3};
        $total += $number;
        printf "%12s = %12.0f\n", $1, $number;;
    }
}

printf "Total %.0f bytes\n", $total;

:

       54.4M =     54400000
        3.2G =   3200000000
          1K =         1000
        0.1M =       100000
Total 3254501000 bytes
+1

. , ( "K" ) , (, ):

#!/usr/bin/perl -w

use strict;
use POSIX qw(floor);

my $string = "54.4M";

if ( $string =~ m/(\d+)?.(\d+)([M|G])/ ) {
    my $mantissa = "$1.$2";
    if ( $3 eq "M" ) {
        $mantissa *= (2 ** 20);
    }
    elsif ( $3 eq "G" ) {
        $mantissa *= (2 ** 30);
    }
    print "$string = ".floor($mantissa)." bytes\n";
}

:

54.4M = 57042534 bytes
+1

Source: https://habr.com/ru/post/1739406/


All Articles