Perl, Trim White Space from a String
When we grep a bunch of string, there are white spaces where we wish to trim, especially the white space at the beginning and the end of a string. There is no trim function in Perl like trim in PHP. The Perl function below should help you to trim the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#!/usr/bin/perl sub trim($); sub ltrim($); sub rtrim($); sub trim($) { my $trim_string = shift; $trim_string =~ s/^\s+//; $trim_string =~ s/\s+$//; return $trim_string; } sub ltrim($) { my $trim_string = shift; $trim_string =~ s/^\s+//; return $trim_string; } sub rtrim($) { my $trim_string = shift; $trim_string =~ s/\s+$//; return $trim_string; } my $long_string = " \t foo foo bar \t \t bar "; print trim($long_string); |
Might want to use String::Strip it’s faster. See this previous IronMan post http://www.illusori.co.uk/perl/2010/03/05/advanced_benchmark_analysis_1.html
Thanks, will look into that 😀