user380892
user380892

Reputation: 17

Number formatting with substr

Can anyone explain the logic behind what is happening in this code? I know what its purpose is, but not exactly how it works.

for ( my $i = -3; $i > -1 * length($x); $i -= 4 )
{
substr( $x, $i, 0 ) = ',';
print $x;
}

Upvotes: 0

Views: 49

Answers (1)

choroba
choroba

Reputation: 241968

Print the value of $i to see what's going on:

#! /usr/bin/perl
use warnings;
use strict;

my $x = 1234567890;

for (my $i = -3; $i > -1 * length $x; $i -= 4) {
    substr( $x, $i, 0 ) = ',';
    print "($i)<$x>\n";
}

Output:

(-3)<1234567,890>
(-7)<1234,567,890>
(-11)<1,234,567,890>

Negative position in substr means "count from the right". Specifying length 0 means we're inserting a substring. We're adding commas before each group of 3 digits from the right, but we need to change the position by -4 because we need to jump over the comma added in the previous step.

Upvotes: 3

Related Questions