perl的格式化输出,顺便再提一下chomp的重要性

perl格式化输出的一例,learning 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个字符
}

下面是没有chomp的程序:

print "please input some lines,then press Ctrl+Z. \n";
@s=<STDIN>;
print "1234567890"x 3 ."\n";
foreach $s(@s)
{
printf "%20s\n",$s;
}


下面为输出结果:

有chomp的:

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的:

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 当做一个字符。

第二部分:

如果我们自己指定字符串的宽度,那么程序如下:

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+转行符,得到了这种结果
s
%30
s






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值