perl的格式化输出及chomp的重要性分析
时间:2022-03-22 11:03:00
#!/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
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中datetime常用时间处理方法
Python设计模式中的结构型桥接模式
![](https://img.aspxhome.com/file/2023/1/63901_0s.png)
Python常用Web框架Django、Flask与Tornado介绍
浅谈flask源码之请求过程
Python类的继承和多态代码详解
![](https://img.aspxhome.com/file/2023/6/86166_0s.png)
CSS 的优先规则
Python OpenCV特征检测之特征匹配方式详解
![](https://img.aspxhome.com/file/2023/0/77580_0s.jpg)
基于wxPython的GUI实现输入对话框(1)
![](https://img.aspxhome.com/file/2023/5/124805_0s.jpg)
python实现线程池的方法
Python JSON格式数据的提取和保存的实现
python如何对数组进行降维
![](https://img.aspxhome.com/file/2023/0/112940_0s.png)
十个Python程序员易犯的错误
Dreamweaver MX 2004 之 Flash Element
![](https://img.aspxhome.com/file/UploadPic/20071/200713110301677s.gif)
linecache模块加载和缓存文件内容详解
解决php-fpm.service not found问题的办法
讲解SQL Server海量数据导入的最快方法
Keras中的多分类损失函数用法categorical_crossentropy
![](https://img.aspxhome.com/file/2023/5/63935_0s.jpg)
Python+OpenCV实现图像融合的原理及代码
![](https://img.aspxhome.com/file/2023/9/101239_0s.jpg)
浅谈Python中的字符串
![](https://img.aspxhome.com/file/2023/9/133719_0s.jpg)