chop是去掉字符串的最后一个字符
chomp是去掉“$/”指定的结尾符号
测试程序一:
[perl]
#!/bin/perl
$tmp = "sincere";
chop($tmp);
print "$tmp";
$tmp = "sincere";
chomp($tmp);
print "$tmp";
[/perl]
输出:
[code]
[sincerefly@localhost perl]$ perl chop-chomp
sinceresincere[sincerefly@localhost perl]$
[/code]
测试程序二:
[perl]
#!/bin/perl
$tmp = "sincere\n\n\n";
chop($tmp);
print "$tmp";
$tmp = "sincere\n\n\n";
chomp($tmp);
print "$tmp";
[/perl]
输出:
[code]
[sincerefly@localhost perl]$ perl chop-chomp2
sincere
sincere
[sincerefly@localhost perl]$
[/code]
结论:chop去掉了最后一个字符,chomp去掉了最后一个换行符号
测试程序三:
[perl]
#!/bin/perl
$/ = "";
$tmp = "sincere\n\n\n";
chop($tmp);
print "$tmp";
$tmp = "sincere\n\n\n";
chomp($tmp);
print "$tmp";
[/perl]
输出:
[code]
[sincerefly@localhost perl]$ perl chop-chomp3
sincere
sincere[sincerefly@localhost perl]$
[/code]
结论:当变量“$/”为空串时,chomp函数删除所有的换行标志
测试程序四:
[perl]
#!/bin/perl
$/ = "cere";
$tmp = "sincere\n";
chop($tmp);
print "$tmp";
$tmp = "sincere\n";
chomp($tmp);
print "$tmp";
[/perl]
输出:
[code]
[sincerefly@localhost perl]$ perl chop-chomp4
sincer
sin
[sincerefly@localhost perl]$
[/code]
输出时在print中加入换行,方便观察
结论:成功删除了变量“$/”指定的换行
注:
1,chomp($text=); 一般这样写来从终端读入不带换行的数据
2,“$/”不应该全局更改,并且在文件中使用完成后恢复原值是一个好习惯