use strict; while () { s/(\d+|\.)/ $1 eq '.' ? '' : sprintf "%03d", $1 /eg; print; } __DATA__ 127.0.0.1 256.123.12.1 256.12.31.21