前言 :
在進行字串比對時, 常常因為開頭或結尾多了一個(或多個)空白而比對失敗, 那麼這個 trim() 函式便能幫上忙.
範例代碼 :
- #!/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;
- }
* Perl Regular Expressions By Example
* Perl Black Book: The Most Comprehensive Perl Reference Available Today
* Perl in a Nutshell
沒有留言:
張貼留言