TCL learning notes

xiaoxiao2021-03-06  40

2004/12/28 ★ Regular Expression to Parse The Display Environment Variable.

Set Env (Display) Corvina: 0.1

Regexp {([^:] *):} $ env (Display) Match Host

=> 1

SET MATCH

=> Corvina:

Set host

=> Corvina

The Example Usess Regexp to Pick The Hostname Out of the Display Environment - DISPLIRONMENT

Variable, Which Has The Form:

Hostname: DISPLAY

The Pattern Involves a Complementary Set, [^:], to match anything except

a colon. it uses repetition, *, to repeat That Zero or more Times. Then, IT Groups

That Part Ine SubExpression with Parenthese. The Litral Colon Ensures That

The Display Value Matches The Format We Expect. The Part of The String That

Matches the pattern will be stiled into the match variable. The part we

Really Want Is What matches the subpattern, and this will be stored Into Host.

The Whole Pattern Has Been Grouped with braces to avoid the special meaning of

The Square Brackets To The Tcl Interpreter. without Braces It Would Be:

Regexp (/ [^:] *): $ ENV (Display) Match Host

This Is Quite a Powerful Statement, And It Is Efficient. IF We Only Had T

String command to work with, we would have had to resort to the folowing,

Which Takes Roughly TWICE As long to interpret.

Set i [String First: $ ENV (Display)]

IF {$ I> = 0} {

Set host [String Range $ env (Display) 0 [expr $ I-1]]]]]]]]

}

Multiple Subpatterns are allowed. We can IMPROVE OUR PATTERN SO THAT IT

28 strings and pattern matching chap.2

CREATED:

Decemcer 15, 1994

-Strings.fm3-Copyright Prentice Hall-Draft:

1/11/95

Extracts The Screen Part of The Display As Well As The Host:

Regexp {([^:] *): (. )} $ env (Display) Match host Screen

★ FAQ: EXEC

% Set Paddress [YPMATCH $ Host Hosts]; PUTS $ PADDRESS

200.61.250.220 GSNCD20

% Set Paddress [Exec Ypmatch $ Host Hosts]; Puts $ Paddress200.61.250.220 gsncd20 _

The first case Paddress is empty

★ FAQ: SET

Set i a

Declaring a variable name I I

SET $ I 1

A variable of "Name $ I", this monster can be examined in [EXPR $$ I], but PUTS $ {$ I} is not defined, and the variable is not defined. Puts $$ i get $ A and I don't know what to do, but if I can't declare i, $ I will not declare success.

The same thing is in Command, etc. PUTS / GETS, etc.

(2005/1/4: Finally, the reason is that SET $ I 1 is actually resolved to set a 1, which is assigned to variable A, and another way is set [set i])

★ FAQ: ENV

$ ENV (Display)

When used in a function, be sure to remember to declare it for global variables:

Global ENV

Another Variables defined by tclsh. (Can also use the info vars command to find out what is defined.)

argc The number of command line argumentsargv A list of the command line argumentsargv0 The name of the script being executed. If being used interactively, argv0 is the name of the shell program.env An array of the environment variables. See page 38.tcl_interactive True (one) if the tclsh is prompting for commands.tcl_prompt1 If defined, this is a command that outputs the prompt. .tcl_prompt2 If defined, this is a command that outputs the prompt if thecurrent command is not yet complete.auto_path The search path for script library directories. See page 90.auto_index A map from command name to a Tcl command that defines it.auto_noload If set, the library facility is disabled.auto_noexec If set, the auto execute facility is disabled.geometry (wish only). The Value of the -geometry argument.

★ FAQ: How to include files

Use Source "xxxxx.tcl" in the code

2004/12/29 ★ destructor bodyDeclares the body used for the destructor, which is automatically invoked when an objectis deleted. If the destructor is successful, the object data is destroyed and the object nameis removed as a command from the interpreter. If destruction fails , an error message isreturned and the object remains.When an object is destroyed, all destructors in its class hierarchy are invoked in orderfrom most- to least-specific. This is the order that the classes are reported by the "infoheritage" command, and it is exactly the opposite of the default constructor order.2005 / 01/04 ★ set i 1; while $ i <= 10 {incr i} The loop will run indefinitely The bug is that the Tcl interpreter will substitutefor $ i before while. is called, so while gets a constant expression 1 <= 10 thatwill always be true. You can avoid these kinds of errors by adopting a consistentcoding style that always groups expressions and command bodies with curlybraces. ★ string range abcd 1 end => bcd not What String Range ABC D 1 [String Length XXXX]

★ talk formatA position specifier is i $, which means take the value from argument i asopposed to the normally corresponding argument. The position counts from 1. Ifyou group the format specification with double-quotes, you will need to quote the $ with a backslash.set lang 2format "% $ {lang} / $ s" one un uno => unThe position is useful for picking a string from a set, such as this simplelanguage-specific example. The position is also useful if the same value isrepeated In the formatted string. if a position is specified for one format keyword, IT Must be used for all of them. Note% and% N $ cannot be mixed in a statement.

You can compute a field width and pass it to format as one of the argumentsby using * as the field width specifier. In this case the next argument is used asthe field width instead of the value, and the argument after that is the value thatgets formatted .set maxl 8format "% - * s =% s" $ maxl Key ValueDIFFERENCES FROM ANSI SPRINTFThe behavior of the format command is the same as the ANSI C sprintf procedure except for the followingdifferences: [1]% p and% n specifiers are not . currently supported [2] For% c conversions the argument must be a decimal string, which will then be converted to the corresponding character value [3] The l modifier is ignored;. integer values ​​are always converted as if there were no modifier presentand real values ​​are always converted as if the l modifier were present (ie type double is used forthe internal representation). If the h modifier is specified then integer values ​​are truncated to shortbefore conversion.

★ string match {[ab] *} cello => 0Be careful! Square brackets are also special to the Tcl interpreter, so you'llneed to wrap the pattern up in curly braces to prevent it from being interpretedas a nested command.Another approach is To put the pattern info a variable: set pat {[ab] * x} string match $ PAT box => 1

Match One of A Set of Characters: The String Match Function Does Not Support Alternational In a Pattern, Such as the {a, b, c} syntax of the c-shell. The Glob Command, However, Does Support This form.

★ Using Info To Determine IF A Variable Exists.if! [Info EXISTS FOOBAR] {set foobar 0} else {incr foobar}

2004/01/05

★ Tap @ @ @ @, come out, a lot of weird DD :)

SET :: script_dir [file dirname [info script]]]]]]

Set here [pwd]; cd $: script_dir; set :: script_dir [pwd]; cd $ here

Set v (a) a

Set v (a, a) a

! A variable can be either 1 dimensional array or an N-dimensional array.

SET WELCOME [Read [set fh [open $ _welcome r]]] [Close $ fh]

★ Run ONCE CACHE PROC

Proc admin_possible {} {

SET AP [Check_admin_possible]

Proc admin_possible {} [list return $ ap]

Return $ AP

}

Proc Plugin_Mime_Possible {} {

# Do we have access to the mime data?

Set testkey {hkey_classes_root / mime / data / content type / application / x-activState-installer}

IF {[catch {registry set $ testkey}]} {return 0}

Catch {registry delete $ testkey}

Return 1

}

2005/1/15

★ Multi-Switch (Use '-')

Switch $: TCL_PLATFORM (OS) {

Freebsd - linux - OSF1 - Sunos {

# Bugfix: if the path in an entry is to long suns splits

# The entry into two line, one containing the path, the

# 安ot Containing The remainder of the information. this

# Means That Every in The Last Line Moves One Index To The

# Front and Index 3 Refers to the Percentage Instead of

# The available space. Our fix is ​​to count the elements

# from the end, ask, as the available space is the third one

# from the end, and this idnex does not change

# Entry is split in Two Lines.

Return [Lindex [Lindex [Split [EXEC DF -K $ DIR] / N] END] END-2] .0

}

HP-UX {

Return [Lindex [Lindex [Split [EXEC BDF $ DIR] / N] END] 3] .0

}

AIX {

Return [Lindex [Lindex [Split [EXEC DF -K $ DIR] / N] END] 2] .0

}

{Windows NT} - {Windows 95} {

Catch {

Set Dir [File NativeName $ DIR]

SET RES [EVAL EXEC [Auto_Execok Dir] [List $ DIR]]

Set line [lindex [split $ res "/ n"] end]

IF {[regexp -nocase {([0-9, /.] ) / s (bytes | KB | MB) / S } /

$ line -> size type} {

Set size [string map {, {}} $ size]

Switch $ TYPE {

MB - MB {Return [expr {$ size * 1000.0}]}]}

KB - KB {RETURN [EXPR {Double ($ size)}]} bytes - bytes {

IF {[string match {*. *} $ size]} {

Return [expr {$ size / 1024.0}]

} else {

Return [EXPR {Double ($ size) / 1024.0}]

}

}

}

} else {

ERROR "Unable to extract free space for $ dir from output of 'dir'"

}

}

# Some Error Occured, Assume We Have At Least 100MB

Return 100000.0

}

DEFAULT {Error "Unable to get disk free space on $: tcl_platform (os)"}

}

2005/2/16

★ Double quotes compared to the list command.

Set x {1 2}

=> 1 2

Set Y "$ x 3"

=> 1 2 3

Set y [contat $ x 3]

=> 1 2 3

Set Z [List $ x 3]

=> {1 2} 3

The Distinction Between List and Concat Becomes Immistant WHEN TCL Commands

Are Built Dynamically. The Basic Rule Is That List and Lappend Preserve

List structure, While Concat (or Double-Quotes) Eliminate One level of list structure.

The DistInction Can Be Subtle Because There Are Examples Where List and

Concat Return THE SAME RESULTS. Unfortunately, this Can Lead to Data-Dependent

Bugs.

★ lappend

The lappend command is unique among the list-related commands because

ITS First Argument is the name of a list-valued variable, while all the other commersss

Take List Values ​​as arguments. You can call lappend with the name of an

undefined Variable and The Variable Will Be CREATED.

★ DELETING a List element by value.

Proc Ldelete {List value} {

Set ix [lsearch -exact $ list $ value]

IF {$ ix> = 0} {

Return [LREPLACE $ LIST $ IX $ IX]

} else {

RETURN $ LIST

}

}

★ Use Split to Turn Input Data INTO TCL LISTS.

Set line {Welch: *: 3116: 100: Brent Welch: / usr / welch: / bin / csh}

Split $ line:

=> Welch * 3116 100 {BRENT Welch} / usr / welch / bin / csh

Set line {this is "not a tcl list}

Lindex $ LINE 1

=> IS

Lindex $ LINE 2

=> unmatched open quote in list

Lindex [split $ line] 2

=> "Not

★ join

Join {1 {2 {3 3 3}} {4 5}}

=> 1 2 {3 3 3} 4 5

Join [Join {1 {2 {3 3 3}} {4 5}}]

=> 1 2 3 3 3 4 5

转载请注明原文地址:https://www.9cbs.com/read-76037.html

New Post(0)