chomp
语法
chomp VARIABLE
chomp ( LIST )
chomp 是 chop 的安全版本,相对于chop 删除字符串或list最后任意字符。
chomp 只删除 '\n',否则不删除。
VARIABLE == string
例1 :$str ="test function of chomp\n" ;
chomp ($str );
例2 :$str =<STDIN>;
chomp ($str );
上面的二行可以合并为chomp ($str =<STDIN>)
例3 .$test ="string" ;
chop $test ;
print $test ;
备注:
1 .在使用chomp 的时候,可以不使用圆括号(),即chomp $str ;
2 .如果字符串结尾有2 个或2 个以上的换行符\n,chomp 只去掉一个。
3 .如果字符串结尾没有换行符,那chomp 什么都不做,返回0 。
VARIABLE == hash
If VARIABLE is a hash, it chomps the hash's values,
but not its keys, resetting the each iterator in the process
VARIABLE == list
If you chomp a list, each element is chomped,
and the total number of characters removed is returned.
while (<>) {
chomp ;
my @array = split (/:/ );
}
chop和chomp函数区别
chop函数负责删除标量型标量的最后一个字符或数组中每个元素的最后一个字符,并返回修改后的值。
chop一般用于删除程序接收到的输入行末尾的换行符,这些输入行可以来自STDIN、文件或者命令置换结果。
chomp函数,负责删除标量型变量中的最后一个字符,或者数组中每个字的最后一个字符,
并保证只有该行末字符是换行符时才进行删除操作。它会返回删除后的字符数目。
使用chomp函数来代替chop,能避免删除换行符之外的其它字符。