Perl trim function to strip whit…

Perl trim function to strip whitespace from a string

Perl does not have a built-in trim function. Use the subroutine below to trim whitespace (spaces and tabs) from the beginning and end of a string in Perl. This function is directly based on the Perl FAQ entry, How do I strip blank space from the beginning/end of a string?. The ltrim and rtrim functions can trim leading or trailing whitespace.


#!/usr/bin/perl
# Declare the subroutines
sub trim($);
sub ltrim($);
sub rtrim($);
# Create a test string
my $string = "  \t  Hello world!   ";
# Here is how to output the trimmed text "Hello world!"
print trim($string)."\n";
print ltrim($string)."\n";
print rtrim($string)."\n";
# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
 my $string = shift;
 $string =~ s/^\s+//;
 $string =~ s/\s+$//;
 return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
 my $string = shift;
 $string =~ s/^\s+//;
 return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
 my $string = shift;
 $string =~ s/\s+$//;
 return $string;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值