tcl::prefix — 접두사 매칭 유틸리티

tcl::prefix — 접두사 매칭 유틸리티

명령줄 옵션처럼 사용자가 입력한 문자열이 미리 정의된 후보들 중 하나와 "맞는지" 확인해야 할 때가 있어요. 전체 문자열이 아니라 앞부분(접두사)만으로도 매칭되면 편하죠. tcl::prefix는 문자열 리스트에서 접두사를 찾아주는 명령들로 이루어져 있어요.

출처: Tcl Commands — tcl::prefix

본문

::tcl::prefix all table string
::tcl::prefix longest table string
::tcl::prefix match ?option ...? table string

이 문서는 문자열 리스트에서 접두사를 찾아보는 명령들을 설명해요. 지원되는 명령은 다음과 같아요.

::tcl::prefix all table string table에서 접두사 string으로 시작하는 모든 요소의 리스트를 돌려줘요.

::tcl::prefix longest table string table에서 접두사 string으로 시작하는 모든 요소들의 가장 긴 공통 접두사를 돌려줘요.

::tcl::prefix match ?option ...? table string stringtable의 어느 한 요소와 같거나, 정확히 한 요소의 접두사라면, 일치한 요소를 돌려줘요. 그렇지 않으면 결과는 -error 옵션에 따라 달라져요. (이 서브명령 자체의 동작에는 꼭 필요하진 않지만, 오류 메시지에 표시되는 일치 목록도 정렬되도록 table은 이 서브명령과 함께 쓰기 전에 정렬해 두는 것이 권장돼요.) 지원되는 옵션은 다음과 같아요.

-exact 정확히 일치하는 것만 받아들여요.

-message string 불일치 시 오류 메시지에 string을 사용해요. 기본값은 "option"이에요.

-error options 일치하는 항목이 없을 때 이 옵션들이 사용돼요. options가 비어 있으면 오류가 생성되지 않고 빈 문자열이 반환돼요. 그렇지 않으면 오류 메시지를 생성할 때 반환 옵션(return options)으로 사용돼요. 기본값은 "-level 0"을 설정한 것에 해당해요.

예를 들어 "-error {-errorcode MyError -level 1}"을 쓰면 오류는 다음과 같이 생성돼요:

return -errorcode MyError -level 1 -code error \
    "ambiguous option ..."

예제

기본 사용법이에요.

namespace import ::tcl::prefix
prefix match {apa bepa cepa} apa
→ apa
prefix match {apa bepa cepa} a
→ apa
prefix match -exact {apa bepa cepa} a
→ bad option "a": must be apa, bepa, or cepa
prefix match -message "switch" {apa ada bepa cepa} a
→ ambiguous switch "a": must be apa, ada, bepa, or cepa
prefix longest {fblocked fconfigure fcopy file fileevent flush} fc
→ fco
prefix all {fblocked fconfigure fcopy file fileevent flush} fc
→ fconfigure fcopy

옵션 매칭을 단순화하는 예시예요.

array set opts {-apa 1 -bepa "" -cepa 0}
foreach {arg val} $args {
    set opts([prefix match {-apa -bepa -cepa} $arg]) $val
}

접두사를 지원하는 switch를 만드는 예시예요.

switch [prefix match {apa bepa cepa} $arg] {
    apa  { }
    bepa { }
    cepa { }
}

더 알아보기

  • lsearch — 리스트에서 검색해요
  • namespace — 네임스페이스 관리
  • string — 문자열 처리 명령
  • Tcl_GetIndexFromObj — C API에서 인덱스 전환