Artifact [9b9ed7e290]

Login

Artifact 9b9ed7e290fc56af2d978750dda5ebd1016cfeaf0c634b0c9d5048ad296c4be1:


# TIP 105: Add Prefix Matching for Switch
	State:		Withdrawn
	Type:		Project
	Tcl-Version:	8.5
	Vote:		Pending
	Post-History:	
	Author:		Donal K. Fellows <[email protected]>
	Created:	03-Jul-2002
	Obsoleted-By:	195
-----

# Abstract

This TIP adds a new option to the [switch] command to support
matching of strings to unique prefixes of patterns, similar to Tcl's
existing subcommand-name matching or Tk's option-name matching.

# Rationale

When code \(particularly in script libraries\) wants to support shortest
unique prefix matching in the manner of the Tcl core \(as provided by
_Tcl\_GetIndexFromObj_\) currently either the prefixes have to be
precomputed \(by hand or by script\) or the matching has to be done
backwards.  In the first case, this is either error-prone or requires
an extra piece of code that has to be developed by the programmer.  In
the second case, the code has to be converted into a pattern which is
matched against the list of supported options in some way, which is
either inefficient or has hazards if the string being matched contains
characters that are meaningful to the matching engine being used.
Instead, it would be far nicer if we could make the core support this
directly, so that script authors could just say what they mean.

# Proposed Change

To support this, I propose modifying the _switch_ command to take an
extra option _-prefix_ \(which should be mutually exclusive with
_-exact_, _-glob_ and _-regexp_ of course\) to enable prefix
matching.  When prefix matching is enabled, the arm chosen for
execution will be the one such that the switch value is identical to
or an unambiguous prefix of its pattern \(i.e. it will not be a prefix
of any other pattern listed, unless the pattern of the arm chosen is
exactly equal to the switch value.\)  If there is no arm whose pattern
is an unambiguous prefix of the switch value, the default arm will be
selected for execution, or if there is no default arm, the switch
command will terminate without an error and with an empty result \(this
is in contrast to the behaviour of _Tcl\_GetIndexFromObj_.\)

# Examples

The command:

	switch -prefix f {
	   foo {
	      puts "matched foo"
	   }
	   bar {
	      puts "matched bar"
	   }
	}

prints "matched foo".  The command:

	switch -prefix b {
	   bar {
	      puts "matched bar"
	   }
	   boo {
	      puts "matched boo"
	   }
	   default {
	      puts "the default action"
	   }
	}

prints "the default action" \("b" is a prefix of two patterns.\)  The
command:

	switch -prefix tcl {
	   tcl {
	      puts "The Tool Command Language"
	   }
	   tk {
	      puts "The Tk Toolkit"
	   }
	   tcl/tk {
	      puts "A cool combination"
	   }
	}

prints "The Tool Command Language" \(although "tcl" is a prefix of two
patterns, it matches one of them exactly.\)

# Copyright

This document has been placed in the public domain.