Copy codeThe Code is as follows :#! /Bin/perl
Print "please input some lines, then press Ctrl + Z. \ n ";
Chomp (@ s = <STDIN> );
Print "1234567890" x 3. "\ n"; # serves as a yardstick for output results.
Foreach $ s (@ s)
{
Printf "% 20s \ n", $ s; # The output format is right-aligned and occupies 20 characters
}
Output result:
F: \> perl \ a. pl
Please input some lines, then press Ctrl + Z.
How are you
Fine, thank you
^ Z
123456789012345678901234567890
How are you # u at 20th characters
Fine, thank you
#------------------------
Programs without chomp:
Copy codeThe Code is as follows :#! /Bin/perl
Print "please input some lines, then press Ctrl + Z. \ n ";
@ S = <STDIN>;
Prints "1234567890" x 3. "\ n ";
Foreach $ s (@ s)
{
Printf "% 20s \ n", $ s;
}
Output result:
F: \> perl \ a. pl
Please input some lines, then press Ctrl + Z.
How are you
Fine, thank you
^ Z
123456789012345678901234567890
How are you # u at 19th characters
Fine, thank you
To observe what is the difference. If chomp is not used, the output result contains not only spaces, but also the final character is 9th, which is equivalent to 19th characters. This is because perl treats a newline as a character.
Part 2:
If we specify the string width, the program is as follows:
Copy codeThe Code is as follows :#! /Bin/perl
Print "Please input column width. \ n ";
Chomp ($ width = <>); # creates a variable. Pay attention to the chomp application here. If chomp is not available, we will not get the desired result.
Print "please input some lines, then press Ctrl + Z. \ n ";
Chomp (@ s = <STDIN> );
Print "1234567890" x7. "\ n ";
Foreach $ s (@ s)
{
Printf "% $ {width} s \ n", $ s; this variable is referenced here, because the maximum character length is used by default for the variable name, here we use {} to define the variable name.
}
Output result:
F: \> perl \ a. pl
Please input column width.
30
Please input some lines, then press Ctrl + Z.
How are you
Fine, thank you
^ Z
1234567890123456789012345678901234567890123456789012345678901234567890
How are you
Fine, thank you
There is no width = <>. If chomp is not passed, the following result is displayed:
F: \> perl \ a. pl
Please input column width.
30
Please input some lines, then press Ctrl + Z.
How are you
Fine, thank you
^ Z
1234567890123456789012345678901234567890123456789012345678901234567890
% 30 # Here, the 30 characters are not removed, and all characters are 30 +. The result is as follows:
% 30
S