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

标签:格式化输出
0
投稿

猜你喜欢

  • Python中datetime常用时间处理方法

    2022-05-03 16:07:06
  • Python设计模式中的结构型桥接模式

    2021-07-23 23:43:31
  • Python常用Web框架Django、Flask与Tornado介绍

    2021-06-24 18:19:35
  • 浅谈flask源码之请求过程

    2023-12-17 10:36:48
  • Python类的继承和多态代码详解

    2022-01-20 14:16:39
  • CSS 的优先规则

    2009-01-08 12:40:00
  • Python OpenCV特征检测之特征匹配方式详解

    2021-07-20 00:51:58
  • 基于wxPython的GUI实现输入对话框(1)

    2023-01-07 19:54:21
  • python实现线程池的方法

    2023-03-10 14:08:06
  • Python JSON格式数据的提取和保存的实现

    2023-03-23 13:27:49
  • python如何对数组进行降维

    2022-12-27 18:51:32
  • 十个Python程序员易犯的错误

    2023-11-27 03:43:13
  • Dreamweaver MX 2004 之 Flash Element

    2010-03-25 12:27:00
  • linecache模块加载和缓存文件内容详解

    2022-09-23 20:00:45
  • 解决php-fpm.service not found问题的办法

    2023-11-21 14:26:21
  • 讲解SQL Server海量数据导入的最快方法

    2008-12-05 16:21:00
  • Keras中的多分类损失函数用法categorical_crossentropy

    2023-06-23 12:25:37
  • Python+OpenCV实现图像融合的原理及代码

    2022-08-01 00:03:52
  • 浅谈Python中的字符串

    2022-10-05 00:39:22
  • ASP编程入门进阶(十三):AdRotator & Content Rotator

    2008-09-24 17:47:00
  • asp之家 网络编程 m.aspxhome.com