Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Truncate leading zeros

Status
Not open for further replies.

AMiSM

Technical User
Jan 26, 2006
128
US
Hi, folks!

Over time, I've needed to change a group of numbers from this:

751,752...1087,1088

to this:
00751,00752...01087,01088

...in other words, I've needed to change a numeric loop variable into something with a consistent number of digits. In the past, I've done this:

$_ = "00000$num";
( $num ) = /(\d{5}$)/;

I'm not really comfortable messing with the default variable all the time, though. Is there a way to do something like this?...

$num =~ m/\d{5}$/;

...though I know this specific example doesn't work. Is there a better way to go about this?
 
Yikes!

Just use sprintf:
Code:
$num = sprintf( '%05d', $num );

# or to do all of them together:
$line = join( ',', map sprintf( '%05d', $_ ), split( ',', $line ) ) ;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top