源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-07-18 10:13 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:perl的格式化输出及chomp的重要性分析
[u]复制代码[/u] 代码如下:
#!/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的程序:
[u]复制代码[/u] 代码如下:
#!/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 当做一个字符。 第二部分: 如果我们自己指定字符串的宽度,那么程序如下:
[u]复制代码[/u] 代码如下:
#!/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)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部