http://www.perlmonks.org?node_id=11133570


in reply to Memeory usage output KB to MB conversion

Your code works, except: (1) You are just moving the decimal so, divide by 1,000 instead of 1024, (2) you should round up, I used the ceil() function for that.

Here is a "hack it with regex" approach:
This doesn't exactly replicate your formatting. But to my eye, it looks "close enough".
I just started adding one regex at a time until I got something "close to desired".
Mileage varies. I used "just a complicated enough" regex for your example. I didn't consider other examples.
Again, mileage varies. But maybe you will see something useful in this hack.
Also, I considered running 5 regexes per line to be of no performance consequence at all.

ADDED: One complication that I did see was, what if Name like "DBMS-db2pb13345" appears? A more complex regex would be needed to skip that. Also from your problem statement, it sounds like sometimes this might need to go KB->GB instead of KB->MB? I'm not sure that that would mean. "Commifiying" the numbers adds a lot of readability. Your sub for that is fine and right out of Perl Cookbook!

use strict; use warnings; use POSIX 'ceil'; #-- Format memory in MB from db2pd -dbptnmem #-- Run as db2pd -dbptnmem | perl -nl db2mem.pl #-- or perl -nl db2mem.pl db2mem.PB1 sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; } while (<DATA>){ print, next if ($.==1); #don't process first line s/KB/MB/g; # all KB->MB s|(\d{2,})|commify(ceil($1/1000));|ge; # move decimal point s| (\d+,)|$1|g; # allow for one comma in al +ignment s| (Mem Used)|$1|; # adjust columns to left 3 +spaces s|===||; # shorten separator 3 colum +ns print; } =OUTPUT Database Member 0 -- Active -- Up 26 days 13:26:26 -- Date 2020-07-10- +10.11.32.332869 Database Member Memory Controller Statistics Controller Automatic: N Controller License Limit: N Controller Limit Enforced: Y Memory Limit: 26,598 MB Current usage: 25,769 MB HWM usage: 26,004 MB Cached memory: 3,353 MB Individual Memory Consumers: Name Mem Used (MB) HWM Used (MB) Cached (MB) ===================================================== APPL-PB1 197 602 39 DBMS-db2pb1 211 211 5 FMP_RESOURCES 23 23 21 PRIVATE 1,378 1,425 844 DB-PB1 23,962 24,334 2,445 =cut __DATA__ Database Member 0 -- Active -- Up 26 days 13:26:26 -- Date 2020-07-10- +10.11.32.332869 Database Member Memory Controller Statistics Controller Automatic: N Controller License Limit: N Controller Limit Enforced: Y Memory Limit: 26597404 KB Current usage: 25768448 KB HWM usage: 26003008 KB Cached memory: 3352576 KB Individual Memory Consumers: Name Mem Used (KB) HWM Used (KB) Cached (KB) ======================================================== APPL-PB1 196352 601792 38272 DBMS-db2pb1 210752 210752 4736 FMP_RESOURCES 22528 22528 20736 PRIVATE 1377280 1424640 843968 DB-PB1 23961536 24333568 2444864