没有使用chomp:
-
#!/bin/perl
-
print "Please input an string and a number by order!n";
-
$the_string= <>;
-
$the_numb= <>;
-
print "The result is n";
-
print "$the_string"x "$the_numb";
结果:
The result is
my
my
my
my
my
加入chomp的情况:
-
#!/bin/perl
-
print "Please input an string and a number by order!n";
-
chomp ( $the_string= <> );
-
chomp ( $the_numb= <> );
-
print "The result is n";
-
print "$the_string"x "$the_numb";
结果:
The result is
mymymymymy
如果字符串结尾有换行符,chomp 可以去掉它。这基本上就是它能完成的所有功能,如下例:
$text = “a line of text/n”; #也可以由输入
chomp($text); #去掉换行符(/n)。
它非常有用,基本上你的每一个程序都会用到它。如你将知道,这是将字符串末尾换行符去掉的最好方法。基于Perl 中的一条基本原则:在需要使用变量的地方,可以使用赋值表达式来代替。我们有更简单的使用chomp 的方法。Perl 首先做赋值运算,再使用这个变量。因此使用chomp 的最常用方法是:
-
chomp ( $text = <STDIN> ); #读入,但不含换行符
-
-
$text = <STDIN>;
-
chomp ( $text ); #同上,但用两步完成
第一眼见到时,第一种组合的方法看起来复杂些。如果把上述其看成两步操作,读一行再chomp,那写成两个语句的方法
看起来自然些。如果将其看作一个操作,读入一行但不包括换行符,那写成一个语句的方法更恰当。由于绝大多数Perl 程序员使用第一种写法,你也应该使用它。
chomp 是一个函数。作为一个函数,它有一个返回值,为移除的字符的个数。这个数字基本上没什么用:
-
$food = <STDIN>;
-
$betty = chomp $food; #得到值1
如上,在使用chomp 时,可以使用或不使用括号()。这又是Perl 中的一条通用规则:除非移除它们时含义会变,否则括号是可以省略的。
如果结尾有两个或两个以上的换行符,chomp 仅去掉一个。如果没有,那什么也不做,返回0。
chop和chomp函数区别
chop函数负责删除标量型标量的最后一个字符或数组中每个元素的最后一个字符,并返回修改后的值。chop一般用于删除程序接收到的输入行末尾的换行符,这些输入行可以来自STDIN、文件或者命令置换结果。
chomp函数,负责删除标量型变量中的最后一个字符,或者数组中每个字的最后一个字符,并保证只有该行末字符是换行符时才进行删除操作。它会返回删除后的字符数目。使用chomp函数来代替chop,能避免删除换行符之外的其它字符。
例1:chop
-
#!/usr/bin/perl
-
$v = 'Flowers';
-
$r = chop ( $v );
-
print "$v (without $r)n";
运行结果
[root@localhost per]# ./1-16.pl
Flower (without s)
例2:chomp
-
#!/usr/bin/perl
-
print "User name: ";
-
$name = < STDIN >;
-
chomp $name;
-
print "Your user name is : $namen";
运行结果
[root@localhost per]# ./1-18.pl
User name: Bill
Your user name is : Bill
本文转载自:http://www.perlcn.com/perlbc/perljc/1655.html