Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: increment # but keep # of digits same

by duff (Parson)
on Apr 26, 2005 at 14:42 UTC ( [id://451597]=note: print w/replies, xml ) Need Help??


in reply to increment # but keep # of digits same

There are two ways to accomplish what you want that immediately come to mind: use sprintf() to ensure the proper number of digits and use the magic increment. The first way is simply $newbuildnum = sprintf("%05d", $oldbuildnum+1) Adjust the 5 as needed. %05d is a format specifier that says output an integer that has a width of 5 characters and is 0 padded.

The second method is kind of sneaky. When you have a variable that holds a string, for instance, $a= "foo" and you do $a++, perl will turn that "foo" into "fop". Another $a++ will get you "foq" and so on. This behavior continues wrapping around at "z" (i.e., $a = "foz"; $a++; would result in $a = "fpa") When the string consists of numbers, perl does the same thing only wrapping at "9". Thus:

#!/usr/bin/perl $a = "00001"; for (0..20) { print $a; $a++ } __END__ 00001 00002 00003 00004 00005 00006 00007 00008 00009 00010 00011 00012 00013 00014 00015 00016 00017 00018 00019 00020 00021

Replies are listed 'Best First'.
Re^2: increment # but keep # of digits same
by Hero Zzyzzx (Curate) on Apr 26, 2005 at 14:51 UTC

    That could simply be:

    #!/usr/bin/perl foreach("00001".."00021"){ print "$_\n"; }

    Edit: Just showing that the increment operator is a bit magical, but now I see I've probably missed the point a bit.

    -Any sufficiently advanced technology is
    indistinguishable from doubletalk.

    My Biz

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://451597]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-03-29 01:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found