Copy Code code as follows:
#!/bin/perl
Print "Please input some lines,then press ctrl+z. \ n";
Chomp (@s=<stdin>);
Print "1234567890" x 3. \ n "; #做为输出结果的一个标尺
foreach $s (@s)
{
printf "%20s\n", $s #输出的格式为右对齐, 20 characters in space
}
Output results:
f:\>perl\a.pl
Please input some lines,then press ctrl+z.
How to Are You
Fine,thank
^z
123456789012345678901234567890
How are you#u at 20th character
Fine,thank
#------------------------
No Chomp program:
Copy Code code as follows:
#!/bin/perl
Print "Please input some lines,then press ctrl+z. \ n";
@s=<stdin>;
Print "1234567890" x 3. \ n ";
foreach $s (@s)
{
printf "%20s\n", $s;
}
Output results:
f:\>perl\a.pl
Please input some lines,then press ctrl+z.
How to Are You
Fine,thank
^z
123456789012345678901234567890
How are you#u at 19th character
Fine,thank
To see what the difference is, if not with Chomp, the output results not only have spaces in the middle, and can find the last character is on the 9th, equivalent to the 19th character. This is because Perl treats a newline as a character.
Part II:
If we specify the width of the string ourselves, then the program is as follows:
Copy Code code as follows:
#!/bin/perl
Print "Please input column width.\n";
Chomp ($width =<>); #新建了一个变量. Here also pay attention to the application of chomp, if there is no chomp, we will not get the results we want.
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 variable name defaults to the maximum character length, all of which we use {} to define the name of the variable.
}
Output results:
f:\>perl\a.pl
Please input column width.
30
Please input some lines,then press ctrl+z.
How to Are You
Fine,thank
^z
1234567890123456789012345678901234567890123456789012345678901234567890
How to Are You
Fine,thank
There is no width=<>, and without chomp, the following result will appear:
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 30 because the change-changers are not removed, all are 30+. , you get this result
%30
S