Computer/etc.

[스크랩] Perl: String trim() - 문자열의 처음과 끝에 있는 공백문자(space,\t,\n,\f) 없애는 방법

수지밝은미소 2007. 10. 22. 13:07

문자열(String)에 포함된 공백문자(whitespace)를 제거하려면,

아래처럼 두 단계를 거치는 방법이 훨씬 빠르고

    for ($string) {
	s/^\s+//;
	s/\s+$//;
    } 
 스칼라(scalar)변수, 어래이(array변수, 해쉬(hash)변수 값들 처음과 끝에 있는
공백문자(whitespace)를 없애는 효과적인 방법은 foreach 문을 사용하여
취환을 수행한다.

foreach ($scalar, @array, @hash{keys %hash}) {

s/^\s+//; s/\s+$//; }

 

trim() Subrutine(function) Example:
sub trim {
  my ($string)= shift; # shift @_
  # for loop is substitution :
# ex) for(@ary) { s/ham/turkey/ } <-- substitution about @ary
  for( $string) {
  s/^\s+//; 
   s/\s+$//;
  }
  return $string;
}
 
usage: 
$str = " \n\t TEST String  ";  
print '', trim( $str), "\n"; # print "TEST String"
 

   

출처: http://perldoc.com/perl5.8.4/pod/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning-end-of-a-string-

How do I strip blank space from the beginning/end of a string?

Although the simplest approach would seem to be

    $string =~ s/^\s*(.*?)\s*$/$1/;  

not only is this unnecessarily slow and destructive, it also fails with embedded newlines. It is much faster to do this operation in two steps:

    $string =~ s/^\s+//;
    $string =~ s/\s+$//;  

Or more nicely written as:

    for ($string) {
	s/^\s+//;
	s/\s+$//;
    }  

This idiom takes advantage of the foreach loop's aliasing behavior to factor out common code. You can do this on several strings at once, or arrays, or even the values of a hash if you use a slice:

    # trim whitespace in the scalar, the array,
    # and all the values in the hash
    foreach ($scalar, @array, @hash{keys %hash}) {
        s/^\s+//;
        s/\s+$//;
    }  

출처 : 마인드스톰 레조스
글쓴이 : lejos 원글보기
메모 :

'Computer > etc.' 카테고리의 다른 글

엑셀-범례 수정하기.  (0) 2008.06.09
리눅스 소스  (0) 2007.12.18
16진수 -> 10진수로  (0) 2007.09.05
hungapp  (0) 2007.08.14
strtok_r : 문자열에서 토큰 뽑아냄.  (0) 2007.07.10