国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Perl > 正文

perl的格式化輸出及chomp的重要性分析

2020-06-04 20:29:32
字體:
來源:轉載
供稿:網友

代碼如下:
#!/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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 息烽县| 依兰县| 凌云县| 南部县| 老河口市| 当雄县| 宁阳县| 宁晋县| 安泽县| 兴宁市| 嘉义市| 十堰市| 从化市| 大竹县| 乌兰察布市| 定边县| 河池市| 五大连池市| 岳阳市| 洛川县| 织金县| 高雄市| 习水县| 法库县| 克山县| 桐庐县| 石泉县| 镇雄县| 乐都县| 永康市| 诸暨市| 桦川县| 南京市| 平遥县| 绥棱县| 绥阳县| 孟村| 永顺县| 普陀区| 阿瓦提县| 巫山县|