chop() and chomp()

本文介绍了Perl语言中chomp()和chop()两个函数的区别及使用方法。chomp()用于移除字符串末尾的换行符,而chop()则移除字符串最后一个字符,无论其为何种字符。通过具体示例展示了这两个函数如何工作,并讨论了它们的应用场景。

by Parham (Friar)
on Jan 01, 2002 at 04:23 UTC

documentation provided for the functions:

 

chomp


This is an alternative to the chop() function. It removes characters at the end of strings corresponding to the $INPUT_LINE_SEPARATOR ($/). It returns the number of characters removed. It can be given a list of strings upon which to perform this operation. When given no arguments, the operation is performed on $_.

chop


This function removes the last character of a string and returns that character. If given a list of arguments, the operation is performed on each one and the last character chopped is returned.
------------------------
these two functions are very much alike... they both remove one (or more) characters from the end of a string... So how are they different you ask? Chomp() ONLY removes new line characters (these are specified in $/), whereas Chop() removes anything that is at the end of the string (it really doesn't care what it is)...
let's demonstrate these two functions:

#chomp() EXAMPLES $a = "abcdefghij"; chomp($a); print $a; #would return exact string... nothing to remove $a = "abcdefghij/n"; chomp($a); print $a; #would return 'abcdefghij', removed newline $a = "abcdefghij/n"; $b = chomp($a); print $b; #would return 1, it did remove something for sure #chop() EXAMPLES $a = "abcdefghij"; chop($a); print $a; #this would return 'abcdefghi' $a = "abcdefghij"; $b = chop($a); print $b; #this would return 'j'

[download]

remember.. this with a little bit of usefulness chop() can be the same as chomp()

$a = "abcdefghij/n"; if ($a =~ //n$/) { chop $a; } #this could also be /r/n if on windows p +latform

[download]

most of the time, you'll want to chomp(), but you might want to use chop() with regexes for the same output
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值