tags:

views:

100

answers:

6

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

Thanks Community !

A: 

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.

weismat
A: 
foreach $i (1..99) {printf "%02d\n", $i;}
alamar
+5  A: 

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.

Dave Webb
+1  A: 
printf("%02d\n",$_) foreach (1..20)
ghostdog74
+8  A: 

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";
}
Porculus
+1 That's awesome. I didn't know you could use the range operator with strings like that.
Dave Webb
A: 

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'"
Robert P