Tcl – Decisions

Tcl – Decisions ”; Previous Next Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Tcl language uses the expr command internally and hence it’s not required for us to use expr statement explicitly. Tcl language provides following types of decision making statements − Sr.No. Statement & Description 1 if statement An ”if” statement consists of a Boolean expression followed by one or more statements. 2 if…else statement An ”if” statement can be followed by an optional ”else” statement, which executes when the Boolean expression is false. 3 nested if statements You can use one ”if” or ”else if” statement inside another ”if” or ”else if” statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You can use one switch statement inside another switch statement(s). The ? : Operator We have covered conditional operator ? : in previous chapter, which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ”? expression” is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ”? expression.” If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. An example is shown below. Live Demo #!/usr/bin/tclsh set a 10; set b [expr $a == 1 ? 20: 30] puts “Value of b is $bn” set b [expr $a == 10 ? 20: 30] puts “Value of b is $bn” When you compile and execute the above program, it produces the following result − Value of b is 30 Value of b is 20 Print Page Previous Next Advertisements ”;

Tcl – Strings

Tcl – Strings ”; Previous Next The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language. These strings can contain alphanumeric character, just numbers, Boolean, or even binary data. Tcl uses 16 bit unicode characters and alphanumeric characters can contain letters including non-Latin characters, number or punctuation. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false. String Representations Unlike other languages, in Tcl, you need not include double quotes when it”s only a single word. An example can be − Live Demo #!/usr/bin/tclsh set myVariable hello puts $myVariable When the above code is executed, it produces the following result − hello When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below − Live Demo #!/usr/bin/tclsh set myVariable “hello world” puts $myVariable set myVariable {hello world} puts $myVariable When the above code is executed, it produces the following result − hello world hello world String Escape Sequence A character literal can be a plain character (e.g., ”x”), an escape sequence (e.g., ”t”), or a universal character (e.g., ”u02C0”). There are certain characters in Tcl when they are preceded by a backslash they will have special meaning and they are used to represent like newline (n) or tab (t). Here, you have a list of some of such escape sequence codes − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab Following is the example to show a few escape sequence characters − Live Demo #!/usr/bin/tclsh puts “HellotWorldnnTutorialspoint”; When the above code is compiled and executed, it produces the following result − Hello World Tutorialspoint String Command The list of subcommands for string command is listed in the following table − Sr.No. Methods & Description 1 compare string1 string2 Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1 comes before string2, else 1. 2 first string1 string2 Returns the index first occurrence of string1 in string2. If not found, returns -1. 3 index string index Returns the character at index. 4 last string1 string2 Returns the index last occurrence of string1 in string2. If not found, returns -1. 5 length string Returns the length of string. 6 match pattern string Returns 1 if the string matches the pattern. 7 range string index1 index2 Return the range of characters in string from index1 to index2. 8 tolower string Returns the lowercase string. 9 toupper string Returns the uppercase string. 10 trim string ?trimcharacters? Removes trimcharacters in both ends of string. The default trimcharacters is whitespace. 11 trimleft string ?trimcharacters? Removes trimcharacters in left beginning of string. The default trimcharacters is whitespace. 12 trimright string ?trimcharacters? Removes trimcharacters in left end of string. The default trimcharacters is whitespace. 13 wordend findstring index Return the index in findstring of the character after the word containing the character at index. 14 wordstart findstring index Return the index in findstring of the first character in the word containing the character at index. Examples of some commonly used Tcl string sub commands are given below. String Comparison #!/usr/bin/tclsh set s1 “Hello” set s2 “World” set s3 “World” puts [string compare $s1 $s2] if {[string compare $s2 $s3] == 0} { puts “String ”s1” and ”s2” are same.”; } if {[string compare $s1 $s2] == -1} { puts “String ”s1” comes before ”s2”.”; } if {[string compare $s2 $s1] == 1} { puts “String ”s2” comes after ”s1”.”; } When the above code is compiled and executed, it produces the following result − -1 String ”s1” and ”s2” are same. String ”s1” comes before ”s2”. String ”s2” comes after ”s1”. Index of String Live Demo #!/usr/bin/tclsh set s1 “Hello World” set s2 “o” puts “First occurrence of $s2 in s1” puts [string first $s2 $s1] puts “Character at index 0 in s1” puts [string index $s1 0] puts “Last occurrence of $s2 in s1” puts [string last $s2 $s1] puts “Word end index in s1” puts [string wordend $s1 20] puts “Word start index in s1” puts [string wordstart $s1 20] When the above code is compiled and executed, it produces the following result − First occurrence of o in s1 4 Character at index 0 in s1 H Last occurrence of o in s1 7 Word end index in s1 11 Word start index in s1 6 Length of String Live Demo #!/usr/bin/tclsh set s1 “Hello World” puts “Length of string s1” puts [string length $s1] When the above code is compiled and executed, it produces the following result − Length of string s1 11 Handling Cases Live Demo #!/usr/bin/tclsh set s1 “Hello World” puts “Uppercase string of s1” puts [string toupper $s1] puts “Lowercase string of s1” puts [string tolower $s1] When the above code is compiled and executed, it produces the following result − Uppercase string of s1 HELLO WORLD Lowercase string of s1 hello world Trimming Characters Live Demo #!/usr/bin/tclsh set s1 “Hello World” set s2 “World” puts “Trim right $s2 in $s1” puts [string trimright $s1 $s2] set s2 “Hello” puts “Trim left $s2 in $s1″ puts [string trimleft $s1 $s2] set s1 ” Hello World ” set s2 ” ” puts “Trim characters s1 on both sides of s2” puts [string trim $s1 $s2] When the above code is compiled and executed, it produces the following result − Trim right World in Hello World Hello Trim left Hello in Hello World World Trim characters s1 on both sides of s2 Hello World Matching Strings Live Demo #!/usr/bin/tclsh set s1 “[email protected]” set s2 “*@*.com” puts “Matching pattern s2 in s1” puts [string match “*@*.com” $s1 ] puts “Matching pattern tcl in s1” puts [string match {tcl} $s1] When the above code is compiled and executed, it produces the following result − Matching pattern

Tcl – Overview

Tcl – Overview ”; Previous Next Tcl is shortened form of Tool Command Language. John Ousterhout of the University of California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter that gets embedded to the application, we develop with it. Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn Shell (sh), and Perl. It aims at providing ability for programs to interact with other programs and also for acting as an embeddable interpreter. Even though, the original aim was to enable programs to interact, you can find full-fledged applications written in Tcl/Tk. Features of Tcl The features of Tcl are as follows − Reduced development time. Powerful and simple user interface kit with integration of TK. Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform. Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days. You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C++, or Java to Tcl or vice versa. Have a powerful set of networking functions. Finally, it”s an open source, free, and can be used for commercial applications without any limit. Applications Tcl is a general-purpose language and you can find Tcl everywhere. It includes, Scalable websites that are often backed by databases. High performance web servers build with TclHttpd. Tcl with CGI based websites. Desktop GUI applications. Embedded applications. Print Page Previous Next Advertisements ”;

Tcl – Special Variables

Tcl – Special Variables ”; Previous Next In Tcl, we classify some of the variables as special variables and they have a predefined usage/functionality. The list of specials variables is listed below. Sr.No. Special Variable & Description 1 argc Refers to a number of command-line arguments. 2 argv Refers to the list containing the command-line arguments. 3 argv0 Refers to the file name of the file being interpreted or the name by which we invoke the script. 4 env Used for representing the array of elements that are environmental variables. 5 errorCode Provides the error code for last Tcl error. 6 errorInfo Provides the stack trace for last Tcl error. 7 tcl_interactive Used to switch between interactive and non-interactive modes by setting this to 1 and 0 respectively. 8 tcl_library Used for setting the location of standard Tcl libraries. 9 tcl_pkgPath Provides the list of directories where packages are generally installed. 10 tcl_patchLevel Refers to the current patch level of the Tcl interpreter. 11 tcl_platform Used for representing the array of elements with objects including byteOrder, machine, osVersion, platform, and os. 12 tcl_precision Refers to the precision i.e. number of digits to retain when converting to floating-point numbers to strings. The default value is 12. 13 tcl_prompt1 Refers to the primary prompt. 14 tcl_prompt2 Refers to the secondary prompt with invalid commands. 15 tcl_rcFileName Provides the user specific startup file. 16 tcl_traceCompile Used for controlling the tracing of bytecode compilation. Use 0 for no output, 1 for summary, and 2 for detailed. 17 tcl_traceExec Used for controlling the tracing of bytecode execution. Use 0 for no output, 1 for summary, and 2 for detailed. 18 tcl_version Returns the current version of the Tcl interpreter. The above special variables have their special meanings for the Tcl interpreter. Examples for using Tcl special variables Let”s see some examples for special variables. Tcl version Live Demo #!/usr/bin/tclsh puts $tcl_version When you run the program, you will get a similar output as shown below − 8.6 Tcl Environment Path Live Demo #!/usr/bin/tclsh puts $env(PATH) When you run the program, you will get a similar output as shown below − /home/cg/root/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/ System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/webmaster/.local/bin:/ home/webmaster/bin:/usr/local/scriba/bin:/usr/local/smlnj/ bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/ local/dart/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/opt/mono/ bin:/opt/mono/lib/mono/4.5:/usr/local/bin:.:/usr/libexec/sdcc:/usr/local/ icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/jdk1.7.0_75/bin:/ opt/jdk1.7.0_75/jre/bin:/opt/pash/Source/PashConsole/bin/Debug/ Tcl Package Path Live Demo #!/usr/bin/tclsh puts $tcl_pkgPath When you run the program, you will get a similar output as shown below − /usr/lib64/tcl8.6 /usr/share/tcl8.6 /usr/lib64/tk8.6 /usr/share/tk8.6 Tcl Library Live Demo #!/usr/bin/tclsh puts $tcl_library When you run the program, you will get a similar output as shown below − /usr/share/tcl8.6 Tcl Patch Level Live Demo #!/usr/bin/tclsh puts $tcl_patchLevel When you run the program, you will get a similar output as shown below − 8.6.6 Tcl Precision Live Demo #!/usr/bin/tclsh puts $tcl_precision When you run the program, you will get a similar output as shown below − 0 Tcl Startup File Live Demo #!/usr/bin/tclsh puts $tcl_rcFileName When you run the program, you will get a similar output as shown below − ~/.tclshrc Print Page Previous Next Advertisements ”;

Tk – Widgets Overview

Tk – Widgets Overview ”; Previous Next The basic component of a Tk-based application is called a widget. A component is also sometimes called a window, since, in Tk, “window” and “widget” are often used interchangeably. Tk is a package that provides a rich set of graphical components for creating graphical applications with Tcl. Tk provides a range of widgets ranging from basic GUI widgets like buttons and menus to data display widgets. The widgets are very configurable as they have default configurations making them easy to use. Tk applications follow a widget hierarchy where any number of widgets may be placed within another widget, and those widgets within another widget. The main widget in a Tk program is referred to as the root widget and can be created by making a new instance of the TkRoot class. Creating a Widget The syntax for creating a widget is given below. type variableName arguments options The type here refers to the widget type like button, label, and so on. Arguments can be optional and required based on individual syntax of each widget. The options range from size to formatting of each component. Widget Naming Convention Widget uses a structure similar to naming packages. In Tk, the root window is named with a period (.) and an element in window, for example button is named .myButton1. The variable name should start with a lowercase letter, digit, or punctuation mark (except a period). After the first character, other characters may be uppercase or lowercase letters, numbers, or punctuation marks (except periods). It is recommended to use a lowercase letter to start the label. Color Naming Convention The colors can be declared using name like red, green, and so on. It can also use hexadecimal representing with #. The number of hexadecimal digits can be 3, 6, 9, or 12. Dimension Convention The default unit is pixels and it is used when we specify no dimension. The other dimensions are i for inches, m for millimeters, c for centimeters and p for points. Common Options There are so many common options available to all widgets and they are listed below in the following table − Sr.No. Syntax & Description 1 -background color Used to set background color for widget. 2 -borderwidth width Used to draw with border in 3D effects. 3 -font fontDescriptor Used to set font for widget. 4 -foreground color Used to set foreground color for widget. 5 -height number Used to set height for widget. 6 -highlightbackground color Used to set the color rectangle to draw around a widget when the widget does not have input focus. 7 -highlightcolor color Used to set the color rectangle to draw around a widget when the widget has input focus. 8 -padx number Sets the padx for the widget. 9 -pady number Sets the pady for the widget. 10 -relief condition Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove. 11 -text text Sets the text for the widget. 12 -textvariable varName Variable associated with the widget. When the text of widget changes, the variable is set with text of widget. 13 -width number Sets the width for widget. A simple example for options is shown below. #!/usr/bin/wish grid [label .myLabel -background red -text “Hello World” -relief ridge -borderwidth 3] -padx 100 -pady 100 When we run the above program, we will get the following output. The list of available widgets are categorized below − Basic widgets Sr.No. Widget & Description 1 Label Widget for displaying single line of text. 2 Button Widget that is clickable and triggers an action. 3 Entry Widget used to accept a single line of text as input. 4 Message Widget for displaying multiple lines of text. 5 Text Widget for displaying and optionally edit multiple lines of text. 6 Toplevel Window with all borders and decorations provided by the Window manager. Layout Widgets Sr.No. Widget & Description 1 Frame Container widget to hold other widgets. 2 Place Widget to hold other widgets in specific place with coordinates of its origin and an exact size. 3 Pack Simple widget to organize widgets in blocks before placing them in the parent widget. 4 Grid Widget to nest widgets packing in different directions. Selection Widgets Sr.No. Widget & Description 1 Radiobutton Widget that has a set of on/off buttons and labels, one of which may be selected. 2 Checkbutton Widget that has a set of on/off buttons and labels, many of which may be selected.. 3 Menu Widget that acts as holder for menu items. 4 Listbox Widget that displays a list of cells, one or more of which may be selected. Mega Widgets Sr.No. Widget & Description 1 Dialog Widget for displaying dialog boxes. 2 Spinbox Widget that allows users to choose numbers. 3 Combobox Widget that combines an entry with a list of choices available to the use. 4 Notebook Tabbed widget that helps to switch between one of several pages, using an index tab. 5 Progressbar Widget to provide visual feedback to the progress of a long operation like file upload. 6 Treeview Widget to display and allow browsing through a hierarchy of items more in form of tree. 7 Scrollbar Scrolling widgets without a text or canvas widgets. 8 Scale Scale widget to choose a numeric value through sliders. Other Widgets Sr.No. Widget & Description 1 Canvas Drawing widget for displaying graphics and images.. We will cover each of these widgets in the upcoming chapters. Print Page Previous Next Advertisements ”;

Tcl – Basic Syntax

Tcl – Basic Syntax ”; Previous Next Tcl is quite simple to learn and let”s start creating our first Tcl program! First Tcl Program Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file. Live Demo #!/usr/bin/tclsh puts “Hello, World!” Assuming, Tcl environment is setup correctly; let”s run the program after switching to file”s directory and then execute the program using − $ tclsh test.tcl We will get the following output − Hello, World! Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command. Comments Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning. Live Demo #!/usr/bin/tclsh # my first program in Tcl puts “Hello World!” When the above code is executed, it produces the following result − Hello World! Multiline or block comment is written using ”if” with condition ”0”. An example is shown below. Live Demo #!/usr/bin/tclsh if 0 { my first program in Tcl program Its very simple } puts “Hello World!” When the above code is executed, it produces the following result − Hello World! Inline comments use ;#. An example is given below. Live Demo #!/usr/bin/tclsh puts “Hello World!” ;# my first print in Tcl program When the above code is executed, it produces the following result − Hello World! Identifiers A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9). Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Whitespace in Tcl A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it. Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement − #!/usr/bin/tclsh puts “Hello World!” There must be at least one whitespace character (usually a space) between “puts” and “Hello World!” for the interpreter to be able to distinguish them. On the other hand, in the following statement − Live Demo #!/usr/bin/tclsh puts [expr 3 + 2] ;# print sum of the 3 and 2 When the above code is executed, it produces the following result − 5 No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose. Print Page Previous Next Advertisements ”;

Tcl – Arrays

Tcl – Arrays ”; Previous Next An array is a systematic arrangement of a group of elements using indices. The syntax for the conventional array is shown below. set ArrayName(Index) value An example for creating simple array is shown below. Live Demo #!/usr/bin/tclsh set languages(0) Tcl set languages(1) “C Language” puts $languages(0) puts $languages(1) When the above code is executed, it produces the following result − Tcl C Language Size of Array The syntax for calculating size array is shown below. [array size variablename] An example for printing the size is shown below. Live Demo #!/usr/bin/tclsh set languages(0) Tcl set languages(1) “C Language” puts [array size languages] When the above code is executed, it produces the following result − 2 Array Iteration Though, array indices can be non-continuous like values specified for index 1 then index 10 and so on. But, in case they are continuous, we can use array iteration to access elements of the array. A simple array iteration for printing elements of the array is shown below. Live Demo #!/usr/bin/tclsh set languages(0) Tcl set languages(1) “C Language” for { set index 0 } { $index < [array size languages] } { incr index } { puts “languages($index) : $languages($index)” } When the above code is executed, it produces the following result − languages(0) : Tcl languages(1) : C Language Associative Arrays In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without any specific order. Associative arrays have an index that is not necessarily a number, and can be sparsely populated. A simple example for associative array with non-number indices is shown below. Live Demo #!/usr/bin/tclsh set personA(Name) “Dave” set personA(Age) 14 puts $personA(Name) puts $personA(Age) When the above code is executed, it produces the following result − Dave 14 Indices of Array The syntax for retrieving indices of array is shown below. [array names variablename] An example for printing the size is shown below. Live Demo #!/usr/bin/tclsh set personA(Name) “Dave” set personA(Age) 14 puts [array names personA] When the above code is executed, it produces the following result − Age Name Iteration of Associative Array You can use the indices of array to iterate through the associative array. An example is shown below. Live Demo #!/usr/bin/tclsh set personA(Name) “Dave” set personA(Age) 14 foreach index [array names personA] { puts “personA($index): $personA($index)” } When the above code is executed, it produces the following result − personA(Age): 14 personA(Name): Dave Print Page Previous Next Advertisements ”;

Swift – Type Casting

Swift – Type Casting ”; Previous Next What is Type Casting in Swift? Type casting is a special feature in Swift, which is used to check the type of the instance or change the type of instance from a class, structure or enumeration to another class, structure or enumeration. It is important because it allows run-time type checking and safe downcasting of instances to subclass types. Swift supports two operators: is and as. The ‘is’ operator is used to check the type of a value and ”as” is used to cast the type value to a different type. Type casting also checks whether the instance type follows a particular protocol conformance standard. Swift supports two types of type casting − Upcasting Downcasting Upcasting in Swift The process of casting an instance of subclass into its base class type is known as upcasting. Or we can say that upcasting is a process in which we treat the instance of a derived class as an instance of its base class. With the help of upcasting, we can only call the methods and properties of the superclass. After upcasting we are not allowed to directly call the methods or properties of the subclass, if you try to do you will get an error. In Swift, upcasting is implicit means we don”t require any special syntax for upcasting, we can directly cast the instance of subclass as the instance of superclass. It is safe to use directly because the instance of the subclass is always treated as the instance of the superclass. Upcasting is commonly used while we are working with polymorphic code or when we want to treat an instance of a different type as the instance of its common base type. Example Swift program for upcasting the instance of the subclass as the instance of the superclass. // Base class class Shape { func display(){ print(“Ball is in the shape of sphere”) } } // Sub class class Rectangle: Shape { func show(){ print(“Rectangle is the most commonly used shape”) } } // Creating an instance of the Rectangle class let rect = Rectangle() // Upcasting the instance of the rectangle class as the instance of the Shape class let obj : Shape = rect // Accessing the method of superclass obj.display() // Now we are not able to directly access the method or properties of the sub-class // If we do we will get an error // obj.show() Output It will produce the following output − Ball is in the shape of sphere Downcasting in Swift The process of casting an instance of a superclass type into a subclass type is known s downcasting. Or we can say that downcasting is a process in which we treat the instance of the base class as an instance of the derived class. It is not necessary that downcasting is always successful, it can be a failure. Swift supports two types of downcasting − Conditional Downcasting(as?) Forced Downcasting(as!) Let”s discuss both of them in detail Conditional Downcasting(as?) The conditional downcasting (as?) operator is used to downcast an instance of the superclass type to a specific subclass type. This operator will return an optional containing the instance of the subclass when the downcast is successful. When the downcast is unsuccessful, then this operator will return nil. This operator is generally used when we are not sure whether the downcast will be a success or not. Syntax Following is the syntax of the conditional downcasting operator(as?) − if let constName = instance as? Type { // Statement that will execute when downcast is successful } else { // Statement that will execute when downcast is unsuccessful } Example Swift program to demonstrate the use of conditional downcasting operator(as?). // Base Class class ProgrammingLanguage { func show() { print(“Welcome to the great world of learning”) } } // Subclass class Swift: ProgrammingLanguage { func display() { print(“Welcome to Swift tutorial”) } } let obj: ProgrammingLanguage = Swift() // Here the conditional downcasting will be successful if let result1 = obj as? Swift { print(“Downcast is successful!”) // Accessing subclass method result1.display() } else { print(“Downcast is unsuccessful”) } // Here the conditional downcasting will be unsuccessful let newObj: ProgrammingLanguage = ProgrammingLanguage() if let result2 = newObj as? Swift { print(“nDowncast is successful!”) result2.display() } else { print(“Downcast is unsuccessful”) } Output It will produce the following output − Downcast is successful! Welcome to Swift tutorial Downcast is unsuccessful Forced Downcasting(as!) The forced downcasting (as!) operator is used to forcefully downcast an instance to a given subclass type. This operator will return an instance of the subclass. If the downcast is unsuccessful, then it will give a runtime error. This operator is generally used when we are sure that downcast will be a success. Syntax Following is the syntax for forced downcasting(as!) − let constantName = instance as! type Example Swift program to demonstrate the use of forced downcasting operator(as!). // Base Class class ProgrammingLanguage { func show() { print(“Welcome to the great world of learning”) } } // Subclass class Swift: ProgrammingLanguage { func display() { print(“Welcome to Swift tutorial”) } } let obj: ProgrammingLanguage = Swift() // Here the forced downcasting will be successful let res1 = obj as! Swift // Accessing the method of Swift class res1.display() // Here the forced downcasting will be successful so we will get an error /*let newobj: ProgrammingLanguage = ProgrammingLanguage() let res2 = newobj as! Swift res2.display()*/ Output It will produce the following output − Welcome to Swift tutorial Type Checking In

Tcl – Operators

Tcl – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Tcl language is rich in built-in operators and provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Ternary Operator This chapter will explain the arithmetic, relational, logical, bitwise, and ternary operators one by one. Arithmetic Operators Following table shows all the arithmetic operators supported by Tcl language. Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then − Show Examples Operator Description Example &plus; Adds two operands A &plus; B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 Relational Operators Following table shows all the relational operators supported by Tcl language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Logical Operators Following table shows all the logical operators supported by Tcl language. Assume variable A holds 1 and variable B holds 0, then − Show Examples Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Bitwise Operators Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 ———————- A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 The Bitwise operators supported by Tcl language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111 Ternary Operator Show Examples Operator Description Example ? : Ternary If Condition is true? Then value X : Otherwise value Y Operators Precedence in Tcl Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example : x = 7 &plus; 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than &plus;, so it first gets multiplied with 3 * 2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Category Operator Associativity Unary &plus; – Right to left Multiplicative * / % Left to right Additive &plus; – Left to right Shift << >> Left to right Relational < <= > >= Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Ternary ?: Right to left Print Page Previous Next Advertisements ”;

Tcl – Home

Tcl/Tk Tutorial PDF Version Quick Guide Resources Job Search Discussion Tcl is a general purpose multi-paradigm system programming language. It is a scripting language that aims at providing the ability for applications to communicate with each other. On the other hand, Tk is a cross platform widget toolkit used for building GUI in many languages. This tutorial covers various topics ranging from the basics of the Tcl/Tk to its scope in various applications. Audience This tutorial is designed for all those individuals who are looking for a starting point of learning Tcl/Tk. Therefore, we cover all those topics that are required for a beginner and an advanced user. Prerequisites Before proceeding with this tutorial, it is advisable for you to understand the basic concepts of computer programming. This tutorial is self-contained and you will be able to learn various concepts of Tcl/Tk even if you are a beginner. You just need to have a basic understanding of working with a simple text editor and command line. Print Page Previous Next Advertisements ”;