gatorreina
gatorreina

Reputation: 960

How to add n number of digits to a string with perl

I need to add a given number of zeros to a string so that the scalar $newstg below comes out to '1000'.

use strict;
my $number_of_zeros = 3;

my $newstg = '1';
$newstg = $newstg . sprintf("%0$number_of_zerosd\n",$subd); 
print "Subd: $newstg\n";

Upvotes: 0

Views: 173

Answers (4)

ikegami
ikegami

Reputation: 385897

$newstg * ( 10 ** $number_of_zeroes )

or

$newstg . ( '0' x $number_of_zeroes )

Upvotes: 1

mob
mob

Reputation: 118605

Use can use the * notation supported by sprintf/printf to use variables in your template.

$newstg .= sprintf("%0*d\n", $number_of_zeros, $subd);
#same as   sprintf("%03d\n", $subd);

Upvotes: 6

simbabque
simbabque

Reputation: 54333

You can use the x repetition operator.

my $number_of_zeros = 3;
print '1' . 0 x $number_of_zeros;

Upvotes: 5

Toto
Toto

Reputation: 91430

It will work fine if you change this line:

$newstg = $newstg . sprintf("%0$number_of_zerosd\n",$subd); 

to

$newstg = $newstg . sprintf("%0${number_of_zeros}d\n",$subd); 
#                             __^             __^

Upvotes: 2

Related Questions