简体   繁体   中英

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";

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);

You can use the x repetition operator .

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

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); 
#                             __^             __^
$newstg * ( 10 ** $number_of_zeroes )

要么

$newstg . ( '0' x $number_of_zeroes )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM