为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

TCL

2011-01-11 50页 ppt 544KB 23阅读

用户头像

is_982505

暂无简介

举报
TCLnullnull Tool Command Language(TCL) Fundamentals null Day-1ObjectivesObjectivesUnderstand the TCL command syntax Incorporate MQL commands into a TCL program Create Matrix Programs that are used as: Methods to build a BOM with roll-up costing Event Triggers to val...
TCL
nullnull Tool Command Language(TCL) Fundamentals null Day-1ObjectivesObjectivesUnderstand the TCL command syntax Incorporate MQL commands into a TCL program Create Matrix Programs that are used as: Methods to build a BOM with roll-up costing Event Triggers to validate and automate an object lifecycle and customize the Matrix environment A program toolset to create a person bulk loader. Language HighlightsLanguage HighlightsTcl is an interpreted “shell” language Supported on multiple platforms (UNIX, DOS, Windows, OS/2, NT, Macintosh) Easily embedded in other applications (Matrix MQL) Extensible with user-defined Tcl commands Simplified syntaxSuggested ReferencesSuggested ReferencesOusterhout, John K. Tcl and the Tk Toolkit Welch, Brent B. Practical Programming in Tcl and Tk Raines, Paul Tcl/Tk Pocket Reference Harrison, Mark Effective Tcl/Tk Programming Jeffrey E. F. Friedl Mastering Regular ExpressionsCapabilitiesCapabilitiesVariables, Arrays and Lists Allows for easy storage and manipulation of data String Manipulation Searching, parsing, and sorting data Flow Control Condition testing, loop control, procedures, and error trapping CapabilitiesCapabilitiesProcedures User defined subroutines and functions File Access Reading, writing, and manipulating files Process Execution Running external programs Environment Set UpEnvironment Set UpText Editor Ascii Text Suggested tools UltraEdit Microsoft Codeview Wordpad Locating Help Tcl on-line help MQL Interactive Help Matrix on-line documentationThe Tcl ShellThe Tcl ShellCommand line interface to the Tcl language Allows the user to enter Tcl commands and have the Tcl interpreter evaluate them Use MQL Interactive window TCL Mode Use WISH.EXE Tk interactive Useful for testing and debugging new Tcl/Tk scriptsTcl ScriptsTcl ScriptsCommands entered in an ASCII text file and then evaluated by the Tcl interpreter Text file evaluated using the source command source “c:/Class Files/MyProgram.tcl” General SyntaxGeneral SyntaxTcl scripts contain one or more Tcl commands separated by newlines or semicolons (;) Tcl commands consist of a set of words separated by spaces. The first word in a Tcl command is the name of the command. The rest of the words are the command arguments. Tcl commands and variables are case sensitive.Tcl CommandsTcl Commandscommandname arg1 arg2 … commandname = Tcl built-in command or user defined procedure name arg = command arguments white space separates commands and arguments newline or semi-colon separate Tcl commandsGeneral SyntaxGeneral SyntaxExample: set iNum 42 set iNum2 43; set iNum3 44VariablesVariablesAll variables are type string All variables and values are case sensitive Variable names and values can be arbitrary strings of characters Declarations are not requiredVariable AssignmentVariable AssignmentValues are assigned to a variable with the set command set sMyvar “Hard Disk” set iCount 23 Accessing Variable ValuesAccessing Variable ValuesDollar sign ($) invokes variable substitution The $ and the following word (variable name) are replaced by the current value of the variable The replaced value is considered to be a single argument to the command, even if it contains spaces Character following $ must be alphanumeric or an underscore Accessing Variable ValuesAccessing Variable ValuesExamples: set sMyvar “Hard Disk” puts $sMyvar => Hard Disk set iCount 23 puts $iCount => 23 SubstitutionSubstitutionDefine how and when values will be substituted for words in a Tcl command Tcl parses a command and makes substitutions in a single pass from left to right The result of one substitution is not scanned for further substitutions Types of substitution rules: Variable Substitution Command Substitution Character SubstitutionVariable SubstitutionVariable SubstitutionDollar Signs ($) invoke variable substitution The $ and the following word (variable name) are replaced by the current value of the variable The replaced value is considered to be a single argument to a command, even if it contains spaces Character following the $ must be a character (not whitespace) Used to access the contents of a variableVariable SubstitutionVariable SubstitutionExample: set sOutput “Print this line” puts $sOutput ==> Print this line Results: The $ causes the sOutput variable to be replaced by it’s value (Print this line) and the puts command prints it to standard outSpecial Variable SubstitutionSpecial Variable SubstitutionVariable is used in expression where variable name is followed by letter or number set sAreaCode (213) puts $sAreaCode555-1212 ==> can't read ”sAreaCode555": no such variable Use ${} for variable substitution puts ${sAreaCode}555-1212 ==> (213)555-1212 Command SubstitutionCommand SubstitutionSquare Brackets ([ ]) invoke command substitution The text inside the brackets is evaluated as a separate Tcl script. The brackets and the text are replaced by the result of that script. Used to nest one Tcl command within another Tcl command Command SubstitutionCommand SubstitutionExample: set iResult [ expr 2 + 2 ] ==> 4 Results: The [ ]’s cause the text inside to be executed as a Tcl command. The result (4) is substituted for the [ ]s and the text, and assigned to the variable. Character SubstitutionCharacter SubstitutionBackslashes (\) invoke character substitution The backslash and following character are removed and replaced with a special character: \a Audible alert \b Backspace \f Form feed \n Newline \r Carriage return \t Tab \v Vertical tab \ddd Octal value ddd \xhh Hex value hh \newline Single space \(all other chars) The character Used to access special charactersCharacter SubsitutionCharacter SubsitutionUse \ newline as the line continuation character in Tcl programs set sParts [mql expand bus \ “System Box” “Metro0001” A from recurse to all]Character SubstitutionCharacter SubstitutionSpecial characters are created using the \ and the reserved character Example: puts “hello \n hello” ==>hello ==> hello Results The \n is replaced by a newline character, and the puts command prints two linesCharacter SubstitutionCharacter SubstitutionThe \ is also used to suppress substitution Example: set sSrc[mql print bus Monitor NEC350 A \ select attribute\[Source\] ] Results: The \ newline on the first line continues the statement. The \[ and \] prevent command substitution from occurring on the attribute Source.GroupingGroupingGrouping is used to combine multiple words into one argument for a command set sMyvar “Hard Disk” Grouping is always performed before substitution when Tcl parses a command Tcl makes a single pass through a statement to determine groups Two types of grouping characters Double Quotes “ “ - Allow substitutions to occur Curly Braces {} - Prevent substitutions in a group Double Quote GroupingDouble Quote GroupingVariable, command, and character substitutions occur as usual within double quotes Any spaces, newlines, and semicolons found between double quotes are considered part of the same command argumentDouble Quote GroupingDouble Quote GroupingExample: set iNum 99 puts “The value of iNum is $iNum” ==> The value of iNum is 99 Results: The multiple words in the puts statement are grouped with double quotes as one argument to puts. Double quotes allow variable substitution to occur on $iNum.Double Quote GroupingDouble Quote GroupingExample: puts “Some text; and more text” ==> Some text; and ==> more text Results: Since the newline and semicolon are within double quotes, they do not terminate the Tcl command. Also, everything within the double quotes is considered to be one word or argument to the puts command.Brace GroupingBrace GroupingVariable, command, and character substitutions DO NOT occur within brace quoting (unless the braces are contained within double-quotes) Braces ({ }) disable all character substitution except backslash-newline (line continuation) Useful to defer evaluation (as in procedures and certain Tcl commands)Brace GroupingBrace GroupingExample: set iCount 99 puts {The value of iCount is $iCount} ==> The value of iCount is $iCount Results: The multiple words in the puts statement are grouped with curly braces as one argument to puts. Curly braces prevent variable substitution to occur on $iCount. Brace GroupingBrace GroupingExample: puts {hello \n hello; $more [text]} ==>hello \n hello; $more [text] Results: All of the special characters (space, \n, $, [, ], and ;) lose their meaning and are printed as normal charactersCommentsCommentsA pound sign (#) designates the start of a comment The comment is terminated by a newline The # must be the first non-blank character of the command Example: # This is a comment puts “hello”; # Need semicolon before # this commentMore Variable CommandsMore Variable CommandsThe following commands are used to manipulate variables: incr append unsetincr Commandincr CommandSyntax: incr varName ?increment? Description: Adds increment (default of 1) to the contents of varName (integer) and places the resulting value in varName Example: set iSize 2 incr iSize 2 puts $iSize ==>4append Commandappend CommandSyntax: append varName value ?value …? Description: Concatenates all the values and appends them to the end of the variable, creating the variable if it doesn’t exist Example: append sPartName Memory “ “ 128 MB puts $sPartName ==>Memory 128MBunset Commandunset CommandSyntax: unset varName ?varName …? Description: Removes variables(s) and their values from memory Example: unset iSize sName Results: The iSize and sName variables are deleted null Day-2 *Control StructuresControl StructuresLike most languages, Tcl supports an if command. The syntax is: if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN? The words then and else are optional, although generally then is left out and else is used. Switch CaseSwitch CaseThe switch command allows you to choose one of several options in your code. The syntax of the command is: switch string pattern1 body1 ?pattern2 body2? ... ?patternN bodyN? - or - switch string { pattern1 body1 ?pattern2 body2?...?patternN bodyN? } If the last pattern argument is the string default, that pattern will match any string.LoopingLoopingTcl includes two commands for looping, the while and for commands.Its basic syntax is while test body The while command evaluates test as an expression. If test is true, the code in body is executed. After the code in body has been executed, test is evaluated again. nullA continue statement within body will stop the execution of the code and the test will be re-evaluated. A break within body will break out of the while loop, and execution will continue with the next line of code after body. For Loop Syntax : for start test next body nullDuring evaluation of the for command, the start code is evaluated once, before any other arguments are evaluated. After the start code has been evaluated, the test is evaluated. If the test evaluates to true, then the body is evaluated, and finally, the next argument is evaluated. After evaluating the next argument, the interpreter loops back to the test, and repeats the process. If the test evaluates as false, then the loop will exit immediately. Example :Example :while {$x < 5} { puts "x is $x" set x [expr {$x + 1}] } for {set i 0} {$i < 10} {incr i} { puts "I inside first loop: $i“ } ExpressionsExpressionsAllows the user to evaluate expressions containing values and operators Values can be integers, reals, strings, or operands Operators can be arithmetic, relational, logical, or bitwise A list of the available operators and their precedence is on page 18 of “Practical Programming in Tcl and Tk”Expression CommandsExpression CommandsThe following command is used to manipulate expressions: expr Expr CommandExpr CommandSyntax: expr arg ?arg arg …? Description: Concatenates all the arguments and evaluates them as an expression Example: expr (10/2) + 3 ==>8 Results: The expression is evaluated and returned as a stringFile AccessingFile AccessingTcl provides several methods to read from and write to files on disk. The simplest methods to access a file are via gets and puts. Basic Syntax: open fileName ?access? ?permission? Opens a file and returns a token to be used when accessing the file via gets, puts, close, etc. nullFileName is the name of the file to open. access is the file access mode r......Open the file for reading. The file must already exist. r+...Open the file for reading and writing. The file must already exist. w.....Open the file for writing. Create the file if it doesn't exist, or set the length to zero if it does exist. nullpermission is an integer to use to set the file access permissions. The default is rw-rw-rw- (0666). You can use it to set the permissions for the file's owner, the group he/she belongs to and for all the other users. For many applications, the default is fine. close fileID Closes a file previously opened with open, and flushes any remaining output. gets fileID ?varName? Reads a line of input from FileID, and discards the terminating newline. nullputs ?-nonewline? ?fileID? String Writes the characters in string to the stream referenced by fileID, read ?-nonewline? fileID Reads all the remaining bytes from fileID, and returns that string. If -nonewline is set, then the last character will be discarded if it is a newline. Any existing end of file condition is cleared before the read command is executed. Using MQL CommandsUsing MQL CommandsAll MQL commands in Tcl are prefixed with the “mql” keyword Use Tcl command substitution to access MQL commands The results of MQL commands are returned to Tcl as a string Results can then be parsed using Tcl commandsMQL Commands in TclMQL Commands in TclExamples: mql list bus Display list of bus objects in Tcl set sPersons [mql list person] Set variable to list of all persons in Matrix set sRole [mql print role Shipper] Set variable to print role output of Shipper null Day-3 ArraysArraysLanguages like C, BASIC, FORTRAN and Java support arrays in which the index value is an integer. Tcl, like most scripting languages (Perl, Python, PHP, etc...) supports associative arrays (also known as "hash tables") in which the index value is a string. The syntax for an associative array is to put the index within parentheses: set name(first) "Mary“ set name(last) "Poppins" puts "Full name: $name(first) $name(last)" nullBelow are the most commonly used Array Commands array exists arrayName array names arrayName ?pattern Returns a list of the indices for the associative array arrayName. If pattern is supplied, only those indices that match pattern are returned. The match is done using the globbing technique from string match. array size arrayName Returns the number of elements in array arrayName. nullarray get arrayName Returns a list in which each odd member of the list (1, 3, 5, etc) is an index into the associative array. The list element following a name is the value of that array member. array set arrayName dataList Converts a list into an associative array. DataList is a list in the format of that returned by array get. Each odd member of the list (1, 3, 5, etc) is an index into the associative array, and the list element following that is the value of that array member. nullarray unset arrayName ?pattern? Unsets all of the elements in the array. If pattern exists, only the elements that match pattern areException HandlingException HandlingIt is possible to "catch" errors and exceptions with the catch command, which runs some code, and catches any errors that code happens to generate. The programmer can then decide what to do about those errors and act accordingly, instead of having the whole application come to a halt. A Tcl proc can also generate an error status condition. This can be done by specifying an error return with an option to the return command, or by using the error command. nullIn either case, a message will be placed in errorInfo, and the proc will generate an error. error message ?info? ?code? Generates an error condition and forces the Tcl call stack to unwind, with error information being added at each step. If info or code are provided, the errorInfo and errorCode variables are initialized with these values. nullcatch script ?varName? Evaluates and executes script. The return value of catch is the status return of the Tcl interpreter after it executes script If there are no errors in script, this value is 0. Otherwise it is 1. If varName is supplied, the value returned by script is placed in varName if the script successfully executes. If not, the error is placed in varName. return ?-code code? ?-errorinfo info? ?-errorcode errorcode? ?value? Generates a return exception condition. nullThe possible arguments are: -code code The next value specifies the return status. code must be one of: ok - Normal status return error - Proc returns error status return - Normal return break - Proc returns break status continue - Proc returns continue status String commandsString commandsstring length string Returns the length of string. string index string index Returns the indexth character from string. string range string first last Returns a string composed of the characters from first to last. string compare string1 string2 Compares string1 to string2 and returns: -1 ..... If string1 is less than string2 0 ........ If string1 is equal to string2 1 ........ If string1 is greater than string2 nullstring first string1 string2 Returns the index of the character in string1 that starts the first match to string2, or -1 if there is no match. string last string1 string2 Returns the index of the character in string1 that starts the last match to string2, or -1 if there is no match. string wordend string index Returns the index of the character just after the last one in the word which contains the index'th character of string. nullstring wordstart string index Returns the index of the character just before the first one in the word which contains the index'th character of string. string match pattern string Returns 1 if the pattern matches string. Usefull list commandsUsefull list commandslsearch list pattern Searches list for an entry that matches pattern, and returns the index for the first match, or a -1 if there is no match. lsort list Sorts list and returns a new list in the sorted order. Ex :set lst [lsort $lst] lrange list first last Returns a list composed of the first through last entries in the list. null Thank You*
/
本文档为【TCL】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索