Using Perl Regular Expressions to Replace substr Calls

August 10, 2011 - 1 minute read -
perl regex regular expressions characters substrings strings

Suppose we want to format digits with commas after the 2nd and 5th digits.
Ie. Convert 12345678 to 12,345,678

Using substr, perl's substring method, this is achieved with:

$old = ‘12345678’
$new = substr( $old, 0, 2 ) . ',' . substr( $old, 2, 3 ) . ',' . substr( $old, 5, 3 ); 
# result: 123,456,78

It works and it’s fine, but perl critic will complain about the use of the numbers 0,2,3 and 5. You could go ahead define them as constants, but that’s cumbersome for trivial substr parameters.

Using a regular expression provides another option.

$old = ‘12345678’
$old =~ m/([d]{2})([d]{3})([d]{3})/;   
$new .= $1 . ',' . $2 . ',' . $3; 
#result: 123,456,78

It’s easily readable to anyone looking at your code and best of all perl critic won’t complain about it.