Falken
Falken

Reputation: 2568

How do I increment a value with leading zeroes in Perl?

It's the same question as this one, but using Perl!

I would like to iterate over a value with just one leading zero.

The equivalent in shell would be:

for i in $(seq -w 01 99) ; do echo $i ; done

Upvotes: 5

Views: 5242

Answers (7)

user14139170
user14139170

Reputation: 11

print  foreach  ("001" .. "099")

Upvotes: 1

Robert P
Robert P

Reputation: 15968

Well, if we're golfing, why not:

say for "01".."99"`

(assuming you're using 5.10 and have done a use 5.010 at the top of your program, of course.)

And if you do it straight from the shell, it'd be:

perl -E "say for '01'..'99'"

Upvotes: 0

Porculus
Porculus

Reputation: 1209

Since the leading zero is significant, presumably you want to use these as strings, not numbers. In that case, there is a different solution that does not involve sprintf:

for my $i ("00" .. "99") {
    print "$i\n";
}

Upvotes: 14

ghostdog74
ghostdog74

Reputation: 342433

printf("%02d\n",$_) foreach (1..20)

Upvotes: 2

David Webb
David Webb

Reputation: 193716

Try something like this:

foreach (1 .. 99) {
   $s = sprintf("%02d",$_);
   print "$s\n";
}

The .. is called the Range Operator and can do different things depending on its context. We're using it here in a list context so it counts up by ones from the left value to the right value. So here's a simpler example of it being used; this code:

@list = 1 .. 10; 
print "@list";

has this output:

1 2 3 4 5 6 7 8 9 10

The sprintf function allows us to format output. The format string %02d is broken down as follows:

  • % - start of the format string
  • 0 - use leading zeroes
  • 2 - at least two characters wide
  • d - format value as a signed integer.

So %02d is what turns 2 into 02.

Upvotes: 11

weismat
weismat

Reputation: 7411

I would consider to use sprinft to format $i according to your requirements. E.g. printf '<%06s>', 12; prints <000012>. Check Perl doc about sprinft in case you are unsure.

Upvotes: 0

alamar
alamar

Reputation: 19321

foreach $i (1..99) {printf "%02d\n", $i;}

Upvotes: 0

Related Questions