How to increase value with leading zeros in Perl?

This is the same question as this one , but using Perl!

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

Equivalent in shell:

for i in $(seq -w 01 99) ; do echo $i ; done 
+4
source share
6 answers

Since the leading zero is significant, it is assumed that you want to use them as strings, not numbers. In this case, there is another solution that does not include sprintf:

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

Try something like this:

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

.. is called a Range Operator and can do different things depending on its context. We use it here in the context of a list, so it counts values ​​from the left value to the right value. So here is a simpler example of its use; this code:

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

has this conclusion:

 1 2 3 4 5 6 7 8 9 10 

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

  • % - beginning of format string
  • 0 - use leading zeros
  • 2 - at least two characters
  • d is the format value as a signed integer.

So %02d is what turns 2 into 02 .

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

I would like to use sprinft to format $ i according to your requirements. For instance. printf '<%06s>', 12; prints <000012> . Check out the Perl doc about sprinft if you are unsure.

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

Well, if we play golf, why not:

 say for "01".."99"` 

(assuming you use 5.10 and, of course, did use 5.010 at the top of your program.)

And if you do it directly from the shell, it will be:

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

Source: https://habr.com/ru/post/1300719/


All Articles