代碼如下:
#!/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個字符
}
輸出結果:
F:/>perl/a.pl
please input some lines,then press Ctrl+Z.
how are you
fine,thank you
^Z
123456789012345678901234567890
how are you#u在第20個字符處
fine,thank you
#------------------------
沒有chomp的程序:
代碼如下:
#!/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;
}
輸出結果:
F:/>perl/a.pl
please input some lines,then press Ctrl+Z.
how are you
fine,thank you
^Z
123456789012345678901234567890
how are you#u在第19個字符處
fine,thank you
來觀察下有什么不同,如果沒有用chomp,輸出的結果不僅中間有空格,并且可以發現最后的字符卻在第9上,相當于在第19個字符處。這是因為perl把a newline 當做一個字符。
第二部分:
如果我們自己指定字符串的寬度,那么程序如下:
代碼如下:
#!/bin/perl
print "Please input column width./n";
chomp($width=<>);#新建了一個變量。這里同樣要注意chomp的應用,如果沒有chomp,我們會得不到我們想要的結果。
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;在這里引用了這個變量,因為變量名默認取最大的字符長度,所有這里我們用{}來界定變量的名稱。
}
輸出結果:
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
下面是沒有width=<>,沒有經過chomp的話,會出現如下結果:
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#這里的30因為沒有去掉轉行符,所有是30+轉行符,得到了這種結果
%30
s
新聞熱點
疑難解答