The 15th chapter of the introduction to the Perl language exercises the 2nd question as follows:
Write a program with the given-when structure, according to the input number, if it can be divisible by 3, print "Fizz", if it can be divisible by 5, print "Bin", if it can be divisible by 7, print "Sausage". For example, if you enter 15, the program should print "Fizz" and "Bin" because 15 can be divisible by 3 and 5 at the same time. Think about what the minimum number of "Fizz Bin sausage" can be for the program to output?
Write your own program as follows:
#!/usr/bin/perl 2 Use 5.010; 3 my $num; 4 while(Chomp($num=<stdin>)){ 5 Next unless $num=~/\a\d+\.? \d+\z/; #防止输入的内容不是数字6Given$num){ 7When (not$_%3 ){ 8 Print "Fizz"; 9 Continue; Ten } OneWhen (not$_%5 ){ A Print "Bin"; - Continue; - } theWhen (not$_%7 ){ - Print "Sausage"; - Continue; - } +Default {Print "\ n";} - } +}
Results when running, found that input 3, 5, 7, no output, and input 15, 35, 21 and other numbers, but can have "Fizz bin", "Bin sausage" and the like output, how is it?
Careful scrutiny, the original problem is on the code of the regular expression on line 5th:
The line code is meant to test whether the input content is a number, if it is not a number, go to the next loop, read the next input, but in the matching pattern, ' \d+ ' requires at least one numeric character to match, then two '\d+' requires at least two numeric characters. As a result, when the input is 3, 5, 7, because it is a single numeric character, and thus can not match normally, entered the next cycle. The solution is to use the '/\a\d+\. \d?/' This pattern to match.
#!/usr/bin/perl 2 Use 5.010; 3 my $num; 4 while(Chomp($num=<stdin>)){ 5 Next unless $num=~/\a\d+\.? \d?\z/; #防止输入的内容不是数字6Given$num){ 7When (not$_%3 ){ 8 Print "Fizz"; 9 Continue; Ten } OneWhen (not$_%5 ){ A Print "Bin"; - Continue; - } theWhen (not$_%7 ){ - Print "Sausage"; - Continue; - } +Default {Print "\ n";} - } +}
Problem Solving!
Perl Learning Notes (2)----an oversight of regular expression number matching