Created
June 9, 2014 17:53
-
-
Save stevelippert/006002418fb9652c44c2 to your computer and use it in GitHub Desktop.
Two different functions to generate human readable bytes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #OLD | |
| sub humanBytes { | |
| my $bytes = shift(@_); | |
| if ($bytes > 1125899906842624){ | |
| return sprintf("%.2f Pb", $bytes / 1125899906842624); | |
| }elsif ($bytes > 1099511627776){ | |
| return sprintf("%.2f Tb", $bytes / 1099511627776); | |
| }elsif ($bytes > 1073741824){ | |
| return sprintf("%.2f Gb", $bytes / 1073741824); | |
| }elsif ($bytes > 1048576){ | |
| return sprintf("%.2f Mb", $bytes / 1048576); | |
| }elsif ($bytes > 1024){ | |
| return sprintf("%.2f Kb", $bytes / 1024); | |
| }else{ | |
| return sprintf("%.0f bytes", $bytes); | |
| } | |
| } | |
| #END OLD | |
| #NEW | |
| sub humanBytes { | |
| my $bytes = shift(@_); | |
| my @units = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'); | |
| my $unit_measure = 0; | |
| while( $bytes >= 1024 ){ | |
| $bytes /= 1024; | |
| $unit_measure++; | |
| } | |
| $bytes = sprintf("%.2f", $bytes); | |
| return "$bytes $units[$unit_measure]"; | |
| } | |
| #END NEW |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment