|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
#######
#
# E-scripts on Tcl/Tk (curso para a Cipsga)
#
# Note 1: use the eev command (defined in eev.el) and the
# ee alias (in my .zshrc) to execute parts of this file.
# Executing this file as a whole makes no sense.
# An introduction to eev can be found here:
#
# (find-eev-quick-intro)
# http://angg.twu.net/eev-intros/find-eev-quick-intro.html
#
# Note 2: be VERY careful and make sure you understand what
# you're doing.
#
# Note 3: If you use a shell other than zsh things like |&
# and the for loops may not work.
#
# Note 4: I always run as root.
#
# Note 5: some parts are too old and don't work anymore. Some
# never worked.
#
# Note 6: the definitions for the find-xxxfile commands are on my
# .emacs.
#
# Note 7: if you see a strange command check my .zshrc -- it may
# be defined there as a function or an alias.
#
# Note 8: the sections without dates are always older than the
# sections with dates.
#
# This file is at <http://angg.twu.net/e/tcl-cipsga.e>
# or at <http://angg.twu.net/e/tcl-cipsga.e.html>.
# See also <http://angg.twu.net/emacs.html>,
# <http://angg.twu.net/.emacs[.html]>,
# <http://angg.twu.net/.zshrc[.html]>,
# <http://angg.twu.net/escripts.html>,
# and <http://angg.twu.net/>.
#
#######
# «.emacs_e_shell» (to "emacs_e_shell")
# «.tclsh_e_mytcl» (to "tclsh_e_mytcl")
# «.widget» (to "widget")
# «.puts_set_expr» (to "puts_set_expr")
# «.if» (to "if")
# «.proc» (to "proc")
# «.quoting» (to "quoting")
# «.statements_e_words» (to "statements_e_words")
# «.substituicoes» (to "substituicoes")
# «.listas» (to "listas")
# «.mywish» (to "mywish")
# «.mywish_src» (to "mywish_src")
# «.sintaxe:wiki» (to "sintaxe:wiki")
# «.tclers_wiki» (to "tclers_wiki")
# «.gets» (to "gets")
# «.manpage-pt» (to "manpage-pt")
#####
#
# Coisas básicas de Emacs e shell
#
#####
# «emacs_e_shell» (to ".emacs_e_shell")
# (find-eev "demo/tutorial.pt.e")
No Emacs:
F3 grava o que está entre os delimitadores "#*" (pro ee)
M-e segue um hiperlink
M-k deleta o "buffer" corrente (bom para voltar de hiperlinks)
C-_ desfaz ("undo") a última mudança no buffer corrente
C-q C-o insere um "*"
M-, < < insere um "«"
M-, > > insere um "»"
M-x eev parecido com o F3, mas grava a região entre o "point" e a "mark"
Obs: no Emacs, "M-tecla" quer dizer "alt-tecla",
e "C-tecla" quer dizer "control-tecla".
No shell:
ee executa o bloco que foi gravado pelo último F3
man 1 tclsh mostra a manpage do tclsh, que mora na seção 1
man tclsh mesma coisa (mas se houvesse manpages para "tclsh"
em várias seções o man poderia escolher a de uma
seção que não era a que a gente queria)
tclsh entra no tclsh ("tcl shell") em modo interativo
mytcl mesma coisa que tclsh, mas disponibilizando umas funções extras
wish um tclsh que vem com o Tk (as funções para ambientes de janelas)
mywish nosso wish com funções extras
mytcl -c 'qualquer seqüência de comandos para Tcl que não contenha
apóstrofes'
executa a seqüência de comandos e sai logo depois, sem entrar
em modo interativo
#####
#
# mytcl (ao invés de tclsh)
#
#####
# «tclsh_e_mytcl» (to ".tclsh_e_mytcl")
# (find-man "1 tclsh")
# (find-fline "~/bin/mytcl")
# (find-fline "~/bin/mywish")
# (find-fline "~/TCL/inc.tcl")
#*
mytcl -c 'puts hello'
mytcl -c 'puts 1+2'
mytcl -c 'puts [expr 1+2]'
#*
* (eepitch-tclsh)
* (eepitch-kill)
* (eepitch-tclsh)
puts hello
puts 1+2
puts [expr 1+2]
#####
#
# Widget
#
#####
# «widget» (to ".widget")
# (find-zsh "dmissing tk | grep /widget")
# (find-zsh "dmissing tk | grep examples/widget")
# (find-fline "/usr/share/doc/tk8.4/examples/widget")
# (find-fline "/usr/share/doc/tk8.5/examples/widget")
#*
* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
wish /usr/share/doc/tk8.4/examples/widget
wish8.5 /usr/share/doc/tk8.5/examples/widget
#*
# (code-c-d "tkex" "/usr/share/doc/tk8.4/examples/")
# (code-c-d "tkex" "/usr/share/doc/tk8.5/examples/")
# (find-tkexfile "")
# (find-tkexfile "widget")
# (find-tkexfile "widget" "text .t")
# (find-tkexfile "widget" ".t tag configure demo")
# (find-tkexfile "widget" ".t tag bind demo")
# (find-tkexfile "widget" "proc showCode")
# (find-tkexfile "widget" "lsearch -glob $tags demo-*")
# (find-tkexfile "widget" "proc showVars")
# (find-tkexfile "widget" "proc invoke")
# (find-tkexfile "widget" "config -text \"Run the")
# (find-man "3tk bind" "\nMODIFIERS")
Janelas: "Widget Demonstration"
um janela para cada demo
Botão "dismiss": fecha a janela desse demo
Botão "see code": abre uma janela "Demo code"
(vai ter no máximo uma de cada vez), editando o código desse demo
Se já existe, faz com que ela carregue de novo o código
"Demo code: (nome do arquivo)"
Idéia: fazer um programinha que abra uma janela de editor em que o M-e
esteja bindado como "executa o texto marcado"
#####
#
# puts, set e expr
#
#####
# «puts_set_expr» (to ".puts_set_expr")
# (find-man "3tcl puts")
# (find-man "3tcl set")
# (find-man "3tcl expr")
#*
* (eepitch-tclsh)
* (eepitch-kill)
* (eepitch-tclsh)
puts 2+2
puts [expr 2+2]
set a 22; puts $a
set a 22; puts $a*3
set a 22; puts [expr $a*3]
set a 22; puts {$a*3}
set a 22; puts [expr {$a*3}]
# (find-man "3tcl puts" "newline character after string")
puts 22 33
puts "22 33"
puts -nonewline 22; puts 33
puts 22; puts 33
#*
#####
#
# if
#
#####
# «if» (to ".if")
#*
# (find-man "3tcl if")
* (eepitch-tclsh)
* (eepitch-kill)
* (eepitch-tclsh)
if 0 then {puts sim} else {puts nao}
if 1 then {puts sim} else {puts nao}
if etc then {puts sim} else {puts nao}
# (find-man "3tcl if")
# As palavras "then" e "else" são opcionais:
if 0 {puts sim} else {puts nao}
if 0 {puts sim} {puts nao}
if 0 then {puts sim} {puts nao}
# A parte do "else" também é opcional.
if 0 {puts sim}
if 1 {puts sim}
#*
#####
#
# proc
#
#####
# «proc» (to ".proc")
# (find-man "3tcl proc")
#*
* (eepitch-tclsh)
* (eepitch-kill)
* (eepitch-tclsh)
proc simnao {x} {
if $x then {puts "$x: sim"} else {puts "$x: nao"}
}
simnao 0
simnao 1
simnao etc
#*
#####
#
# O interpretador
#
#####
# «statements_e_words» (to ".statements_e_words")
# (find-man "3tcl Tcl")
A operação básica do interpretador do Tcl é pegar um string -- um
programa, por exemplo -- e avaliá-lo, i.e., executá-lo (o termo
original em inglês é "evaluate").
A regra é a seguinte: o stringão é divido em "statements", cada
statement é dividido em "words" ("palavras"), e assim que um statement
é entendido como uma seqüência de palavras ele é executado: a primeira
palavra é interpretada como o nome de uma função e as outras são os
parâmetros que são passados para essa função.
À medida que cada palavra é processada vários tipos de "substituições"
e de "quotings" podem acontecer; vamos discutí-los daqui a pouco.
Exemplo:
set x 22; if $x then {puts "$x: sim"} else {puts "$x: nao"}
ssssssss ssssssssssssssssssssssssssssssssssssssssssssssssss
ppp p pp pp pp pppp pppppppppppppppp pppp pppppppppppppppp
$/ {--------------} {--------------}
Quando o Tcl executa a linha grande acima, {set...{puts "$x: nao"}},
ele a divide em dois statements, o primeiro com três palavras, o
segundo com seis; ele executa o primeiro statement, ou seja, chama a
função "set" com parâmetros "x" e "22", e a conseqüência disso é que a
variável x passa a ter o valor 22; depois ele executa o segundo
statement, e chama a função "if" com parâmetros "22" (esse "22" é o
resultado de aplicar as substituições em "$x"), "then", {puts "$x:
sim"}, "else" e {puts "$x: nao"}. Como o "22" é considerado como
"verdadeiro" a função "if" executa a "cláusula then", que é o string
{puts "$x: sim"}; ou seja, ele divide esse string em statements e
palavras e executa cada statement...
puts "$x: sim"
ssssssssssssss
pppp ppppppppp
"-------"
$/
Note que a "cláusula else" não é executada nesse caso (em que o $x é
"verdadeiro"); ela é só um string que o "if" recebe como parâmetro e
descarta imediatamente. Ele não chega nem a ser dividida em
statements! Ou seja, poderíamos ter posto um string arbitrário no
lugar dele e o resultado teria sido o mesmo -- o Tcl não se daria ao
trabalho de detectar se aquele string, quando visto como código Tcl,
tem ou não erros de sintaxe.
#####
#
# substituições
#
#####
# «substituicoes» (to ".substituicoes")
# (find-man "3tcl Tcl")
Caracter Tipo de subst Hiperlink pra manpage
$ Dólar Variável (find-man "3tcl Tcl" "[7]" "Command substitution")
"" Aspas (find-man "3tcl Tcl" "[4]" "Double quotes")
{} Chaves (find-man "3tcl Tcl" "[5]")
\ Contrabarra (find-man "3tcl Tcl" "[8]")
[] Colchetes Comando (find-man "3tcl Tcl" "[6]")
# Lasanha Comentário (find-man "3tcl Tcl" "[9]")
Exemplos:
#*
set a 22; puts $a
set a 22; puts --$a--
set a 22; puts ${a}
set a 22; puts ${a}b
set 99x- 22; puts ${99x-}
set a " x + y"; puts --$a--
#*
set a x+y ; puts --$a--
set a " x+y "; puts --$a--
set a \123; puts --$a--
#*
set b $a\123 ; puts --$b-
set a 22; set b "$a\123"; puts --$b--
set a 22; set b " $a \123 "; puts --$b--
set a 22; set b { $a \123 }; puts --$b--
#*
#####
#
# listas
#
#####
# «listas» (to ".listas")
# (find-man "3tcl lindex")
#*
mytcl -c 'puts <[lindex {a b c} 0]>' ;# -> <a>
mytcl -c 'puts <[lindex {a b c} -1]>' ;# -> <> (não dá erro)
mytcl -c 'puts <[lindex {a b c} 3]>' ;# -> <> (idem)
mytcl -c 'puts <[lindex {a {b c} d} 1]>' ;# -> <b c>
#*
#####
#
# Tk: primeiros programas
#
#####
# «mywish» (to ".mywish")
# (find-angg "LATEX/diaglib.014")
# (find-man "3tk text")
# (find-man "3tk text" "\nTHE SELECTION")
# (find-man "3tk text" "pathName get index1 ?index2?")
#*
mywish -c '
text .t
button .b -command {puts <[.t get sel.first sel.last]>}
pack .t .b
'
#*
mywish -c '
text .t
button .b -text {Roda a parte selecionada} \
-command {eval [.t get sel.first sel.last]}
pack .t .b
'
#*
#####
#
# código fonte do mywish
#
#####
# «mywish_src» (to ".mywish_src")
# (find-node "(bash)Special Parameters")
# (find-es "tcl" "8.3-src")
#*
cat > ~/bin/mywish <<'---'
#!/bin/sh
# Mude de "sh" para "wish": \
exec wish "$0" -- "$@"
source $env(HOME)/TCL/inc.tcl
eval [lindex $argv 1]
---
chmod 755 ~/bin/mywish
#*
wish ~/bin/mywish -- -c 'puts hello; text .t; pack .t'
#*
mywish -c 'puts hello; text .t; pack .t'
#*
# Um detalhe sobre "\\\n"s
# (find-man "3tcl Tcl" "\\<newline>whiteSpace")
# (find-man "3tcl split")
#*
mytcl -c '
set str "puts foo\\\nbar\nputs hello"
puts [split $str ""]
eval $str
'
#*
#####
#
# Sintaxe (explicações do Wiki)
#
#####
# «sintaxe:wiki» (to ".sintaxe:wiki")
# (find-man "3tcl Tcl")
# (find-shttpw3 "mini.net/cgi-bin/wikit/1643.html")
# (find-tclersw3 "1643.html")
Script = commands separated by newlines or semicolons.
Command = words separated by white space.
$ causes variable substitution.
[] causes command substitution.
"" quotes white space and semi-colons.
{} quotes all special characters.
\ quotes next character, provides C-like substitution.
# for comments (must be at beginning of command).
The following hints about the parsing process are probably helpful too:
Word separation (grouping), and variable and command substitution, are
performed in a single pass through a command.
As braces ({}) and double quotes ("") quote white space, their
contents are regarded as a single word by the parser.
The first word in a command is read as the name of a built-in or
defined command procedure.
RS: I would put it this way:
{} group (keep contents together as one word)
"" group and substitute (\,$,[])
[] group(substring), substitute, eval, replace [..] with results
#####
#
# Pacotes Debian
# 2001oct21
#
#####
# (find-status "tk8.3")
# (find-vldifile "tk8.3.list")
# (find-fline "/usr/doc/tk8.3/")
# (find-status "tk8.3-dev")
# (find-vldifile "tk8.3-dev.list")
# (find-fline "/usr/doc/tk8.3-dev/")
# (find-status "tcl8.3-dev")
# (find-vldifile "tcl8.3-dev.list")
# (find-fline "/usr/doc/tcl8.3-dev/")
# (find-status "tcl8.3-doc")
# (find-vldifile "tcl8.3-doc.list")
# (find-fline "/usr/doc/tcl8.3-doc/")
# (find-shttpw3 "mini.net/cgi-bin/wikit/48.html")
#####
#
# Anotações do Maurício
#
#####
Sintaxe / comandos
Tcl possui umas poucas regras de sintaxe que determinam como os
comandos são parseados e um conjunto de comandos
As regras de sintaxe são aprendidas de uma vez por todas, mas os
comandos vão sendo aprendidos gradualmente conforme vão se tornando
necessários
script, comandos e palavras
avaliação de um comando (parseamento e execução)
parseamento - as strings que correspondem aos comandos são quebradas
em palavras e são feitas substituições
na execução são atribuídos significados
Em Tcl se nós queremos avaliação nós precisamos pedí-la explicitamente
(set x 4; set y x+4 - o valor de y é x+4 e não 8)
Substituições: variável, comando, backslash
pode ser usada com vários objetivos incluindo criar nomes
foreach num {1 2 3} ...
citações - com aspas e com chaves
comentários
#*
# (find-man "3tcl info")
mytcl -c 'puts [lsort [info commands]]\n'
mytcl -c 'puts [lsort [info globals]]\n'
mytcl -c 'puts [lsort [info procs]]\n'
#*
mytcl -c 'puts [info args writefile]\n'
mytcl -c 'puts [info body writefile]\n'
#*
#####
#
# Tcler's Wiki
#
#####
# «tclers_wiki» (to ".tclers_wiki")
# (code-c-d "tclers" "/snarf/http/mini.net/tcl/")
# (code-c-d "tclers" "/snarf/http/mini.net/cgi-bin/wikit/")
# (find-tclersw3 "0.html")
# (find-tclersfile "")
# Pra imprimir...
#*
cd $ES
rm -v /tmp/o.p*
a2ps -=p2isol tcl-cipsga.e
make -f ~/LATEX/Makefile /tmp/o.p01
gv /tmp/o.ps
#*
#####
#
# gets
#
#####
# «gets» (to ".gets")
# (find-man "3tcl gets")
#*
mytcl -c 'puts [gets stdin li]; puts <$li>'
#*
echo foo | mytcl -c 'puts [gets stdin li]; puts <$li>'
echo -n foo | mytcl -c 'puts [gets stdin li]; puts <$li>'
echo -n | mytcl -c 'puts [gets stdin li]; puts <$li>'
#*
mytcl -c 'while {[gets stdin li]>=0} {puts [eval $li]}'
#*
mytcl -c 'while {[putstr "% "; gets stdin li]>=0} {puts [eval $li]}'
#*
cat > $EEG <<'---'
expr 1+2
puts foo
exit
---
eeg mytcl -c 'while {[gets stdin li]>=0} {puts [eval $li]}'
#*
#####
#
# Fazendo uma versão em português da manpage
#
#####
# «manpage-pt» (to ".manpage-pt")
# (find-es "man" "manpages-pt")
# (find-tclfile "doc/" "Tcl.n")
# (find-tclfile "doc/Tcl.n")
# (find-tclfile "doc/man.macros")
# (find-tclfile "debian/tcl8.3-doc/usr/share/man/man3/Tcl.3tcl.gz")
# (find-tclfile "odrb")
# (find-tclfile "odrb" "Installing command (.n) docs")
# (find-tclfile "unix/")
# (find-tclfile "unix/Makefile" "Installing command (.n) docs")
# (find-tclfile "unix/mkLinks")
#*
rm -Rv /tmp/tclman/
mkdir /tmp/tclman/
cd /tmp/tclman/
zcat /usr/src/tcl8.3-8.3.1/debian/tcl8.3-doc/usr/share/man/man3/Tcl.3tcl.gz \
> Tcl.3tcl
cp /usr/src/tcl8.3-8.3.1/doc/Tcl.n .
cp /usr/src/tcl8.3-8.3.1/doc/man.macros .
sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \
Tcl.n > Tcl.3tcl.mine
diff Tcl.3tcl*
#*
cp -v /usr/src/tcl8.3-8.3.1/doc/Tcl.n ~/TCL/
cp -v /usr/src/tcl8.3-8.3.1/doc/man.macros ~/TCL/
cd ~/TCL/
sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \
Tcl-pt.n > Tcl-pt.3tcl
laf Tcl*
#*
cd ~/TCL/
cp -v /usr/src/tcl8.3-8.3.1/doc/man.macros .
sed -e '/man\.macros/r man.macros' -e '/man\.macros/d' \
Tcl-pt.n > Tcl-pt.3tcl
cat Tcl-pt.3tcl | groff -Tlatin1 -man |& l -S
# (find-fline "~/TCL/Tcl-pt.n")
#*
mkdir -p /usr/share/man/pt/man3/
# (find-fline "/usr/share/man/pt/man3/")
Tcl(n) Tcl Built-In Commands Tcl(n)
_________________________________________________________________
Nome
Tcl - Sumário da sintaxe da linguagem Tcl.
_________________________________________________________________
DESCRIÇÃO
The following rules define the syntax and semantics of the
Tcl language:
As regras abaixo definem a sintaxe e a semântica da linguagem
Tcl:
[1] A Tcl script is a string containing one or more
commands. Semi-colons and newlines are command
separators unless quoted as described below. Close
brackets are command terminators during command
substitution (see below) unless quoted.
Um script Tcl é um string contendo um ou mais comandos.
Pontos-e-vírgulas e newlines são separadores de
comandos, a menos que estejam "quotados" por chaves,
aspas ou contrabarras, como vai ser descrito abaixo.
Durante uma "substituição de comando" (veja abaixo) um
colchete fechando (``]'') marca o fim de um comando, a
não ser que ele esteja quotado.
[2] A command is evaluated in two steps. First, the
Tcl interpreter breaks the command into words and
performs substitutions as described below. These
substitutions are performed in the same way for all
commands. The first word is used to locate a com-
mand procedure to carry out the command, then all
of the words of the command are passed to the com-
mand procedure. The command procedure is free to
interpret each of its words in any way it likes,
such as an integer, variable name, list, or Tcl
script. Different commands interpret their words
differently.
Um comando é avaliado em dois passos. Primeiro o
interpretador do Tcl separa o comando em palavras e
aplica as substituições descritas abaixo; essas
substituições são aplicadas do mesmo modo em todo os
comandos. A primeira palavra é usada para determinar a
função que vai executar o comando, e todas as outras
palavras do comando são passadas como parâmetros para
essa função. A função é livre para interpretar as
palavras que recebe como parâmetros do modo que quiser,
por exemplo como inteiros, nomes de variáveis, listas ou
scripts de Tcl. Comandos diferentes interpretam seus
parâmetros de modos diferentes.
[3] Words of a command are separated by white space
(except for newlines, which are command separa-
tors).
As palavras de um comando são separadas por espaço em
branco (exceto por newlines, que são separadores de
comandos).
[4] If the first character of a word is double-quote
(``"'') then the word is terminated by the next
double-quote character. If semi-colons, close
brackets, or white space characters (including new-
lines) appear between the quotes then they are
treated as ordinary characters and included in the
word. Command substitution, variable substitution,
and backslash substitution are performed on the
characters between the quotes as described below.
The double-quotes are not retained as part of the
word.
Se o primeiro caracter de uma palavra é aspas (``"'')
então a palavra é terminada pelas próximas aspas. Se
pontos-e-vírgulas, fecha-colchetes, ou caracters de
espaço (incluindo newlines) aparecerem dentro de aspas
eles são tratados como caracteres normais e incluídos na
palavra. Substituições de comandos, substituições de
variáveis e substituições de contrabarras são aplicadas
nos caracteres entre aspas como descrito abaixo. As
aspas não são consideradas como parte da palavra.
[5] If the first character of a word is an open brace
(``{'') then the word is terminated by the matching
close brace (``}''). Braces nest within the word:
for each additional open brace there must be an
additional close brace (however, if an open brace
or close brace within the word is quoted with a
backslash then it is not counted in locating the
matching close brace). No substitutions are
performed on the characters between the braces
except for backslash-newline substitutions
described below, nor do semi-colons, newlines,
close brackets, or white space receive any special
interpretation. The word will consist of exactly
the characters between the outer braces, not
including the braces themselves.
Se o primeiro caracter de uma palavra é uma chave
abrindo (``{'') então a palavra é terminada pela próxima
chave fechando. Chaves podem ocorrer aninhadas: para
cada ``{'' extra deve ocorrer um ''}'' correspondente
para fechá-lo; mas chaves que ocorram quotadas por
contrabarras não são contadas por essa regra. Nenhum
tipo de substituição ocorre entre chaves, exceto pelas
subtituições de pares contrabarra-newline descritas
abaixo. Pontos-e-vírgulas, newlines, fecha-colchetes e
espaço em branco não recebem nenhum tipo de
interpretação especial. A palavra resultante vai ser
exatamente os caracteres entre o ``{'' inicial e o ``}''
correspondente, excluindo o ``{'' e o ``}'' das
extremidades.
[6] If a word contains an open bracket (``['') then Tcl
performs command substitution. To do this it
invokes the Tcl interpreter recursively to process
the characters following the open bracket as a Tcl
script. The script may contain any number of com-
mands and must be terminated by a close bracket
(``]''). The result of the script (i.e. the result
of its last command) is substituted into the word
in place of the brackets and all of the characters
between them. There may be any number of command
substitutions in a single word. Command substitu-
tion is not performed on words enclosed in braces.
Se uma palavra contém um abre-colchetes (``['') então o
Tcl aplica uma substituição de comando. Para isto o
interpretador Tcl invoca a si mesmo recursivamente para
processar os caracteres que vem depois do ``['' como um
script Tcl. O script pode conter qualquer número de
comandos e deve ser terminado por um fecha-colchetes
(``]''). O resultado do script (isto é, o resultado do
seu último comando) é substituído na palavra no lugar
dos colchetes e de todos os caracteres dentro deles.
Substituição de comandos não é aplicada em palavras
entre chaves.
[7] If a word contains a dollar-sign (``$'') then Tcl
performs variable substitution: the dollar-sign
and the following characters are replaced in the
word by the value of a variable. Variable substi-
tution may take any of the following forms:
Se uma palavra contém um ``$'' ("dólar") o Tcl aplica
uma substituição de variável: o dólar e todos os
caracteres seguintes são substituídos na palavra pelo
valor da variável. Substituições de variáveis podem ser
de qualquer uma das formas abaixo:
$name Name is the name of a scalar vari-
able; the name is terminated by any
character that isn't a letter,
digit, or underscore.
Name é o nome de uma "variável escalar";
o nome é terminado por qualquer caracter
que não seja uma letra, dígito ou um
sublinhado (``_'').
$name(index) Name gives the name of an array
variable and index gives the name of
an element within that array. Name
must contain only letters, digits,
and underscores. Command substitu-
tions, variable substitutions, and
backslash substitutions are per-
formed on the characters of index.
Name dá o nome de uma variável de array e
indes dá o nome de um elemento do array.
Name deve conter somente letras, dígitos
e sublinhados. Substituições de comandos,
de variáveis e de contrabarras são
aplicadas nos caracteres do índice.
${name} Name is the name of a scalar vari-
able. It may contain any characters
whatsoever except for close braces.
Name é o nome de uma variável escalar.
Ele pode conter qualquer caracter exceto
por ``}''s.
There may be any number of variable substitutions
in a single word. Variable substitution is not
performed on words enclosed in braces.
Pode haver qualquer número de substituições de variáveis
numa palavra. Substituições de comandos não são
aplicadas em palavras entre chaves.
[8] If a backslash (``\'') appears within a word then
backslash substitution occurs. In all cases but
those described below the backslash is dropped and
the following character is treated as an ordinary
character and included in the word. This allows
characters such as double quotes, close brackets,
and dollar signs to be included in words without
triggering special processing. The following table
lists the backslash sequences that are handled spe-
cially, along with the value that replaces each
sequence.
Se uma contrabarra (``\'') aparece numa palavra ocorre
uma substituição de contrabarra. Em todos os casos
exceto os descritos abaixo a contrabarra é descartada e
o caracter seguinte é tratado como caracter ordinário e
incluído na palavra. O mecanismo de substituição de
contrabarras permite que caracteres como aspas,
fecha-colchetes e dólares sejam incluídos numa palavra
literalmente, sem que eles façam o interpretador entrar
em nenhum dos modo especiais de interpretação. A tabela
seguinte lista as seqüências de caracteres começadas com
contrabarras que são interpretadas de modo especial, e
o resultado de suas substituições.
\a Audible alert (bell) (0x7).
\b Backspace (0x8).
\f Form feed (0xc).
\n Newline (0xa).
\r Carriage-return (0xd).
\t Tab (0x9).
\v Vertical tab (0xb).
\<newline>whiteSpace
A single space character replaces the back-
slash, newline, and all spaces and tabs
after the newline. This backslash sequence
is unique in that it is replaced in a sepa-
rate pre-pass before the command is actually
parsed. This means that it will be replaced
even when it occurs between braces, and the
resulting space will be treated as a word
separator if it isn't in braces or quotes.
\<newline>espaçoEmBranco
A contrabarra, o newline e todos os caracteres de
espaço no começo da linha seguinte (isto é,
espaços e tabs) são substituídos por um único
espaço. Ao contrário de todas as outras
substuições, essas (chamadas de subtituições
contrabarras-newlines) são aplicadas numa espécie
de estágio de pré-processamento que vem antes do
parsing normal, e em que só essas seqüências são
consideradas; isso quer dizer que elas são
substituídas mesmo quando ocorrem entre chaves, e
que o espaço resultante vai ser tratado como
separador de palavras se ocorrer fora de chaves e
aspas.
\\ Backslash (``\'').
\\ Contrabarra (``\'').
\ooo ||
The digits ooo (one, two, or three of them) |
give an eight-bit octal value for the Uni- |
code character that will be inserted. The |
upper bits of the Unicode character will be |
0. |
Os dígitos ooo (um, dois ou três deles) são
interpretados como um valor em octal de oito
bits, e a seqüência é substituída pelo caracter
Unicode correspondente. Os bits mais
significantes desse caracter octal vão ser 0.
\xhh ||
The hexadecimal digits hh give an eight-bit |
hexadecimal value for the Unicode character |
that will be inserted. Any number of hex- |
adecimal digits may be present; however, all |
but the last two are ignored (the result is |
always a one-byte quantity). The upper bits |
of the Unicode character will be 0. |
Os dígitos hexadecimais hh são interpretados como
o código de um caracter Unicode, que é
substituído pela seqüência. Qualquer número de
dígitos hexadecimais pode estar presente, mas só
os dois últimos vão ser considerados; o resultado
sempre corresponde a um byte. Os bytes mais
significantes do caracter Unicode vão ser 0.
\uhhhh ||
The hexadecimal digits hhhh (one, two, |
three, or four of them) give a sixteen-bit |
hexadecimal value for the Unicode character |
that will be inserted.
Os dígitos hexadecimais hhhh (um, dois, três ou
quatro dígitos) dão um valor de 16 bits, e o
caracter Unicode correspondente é substituído
pela seqüência.
Backslash substitution is not performed on words
enclosed in braces, except for backslash-newline as
described above.
Substituição de contrabarras não é aplicada em palavras
entre chaves, exceto pelas substituições de
contrabarra-newlines, como descrito acima.
[9] If a hash character (``#'') appears at a point
where Tcl is expecting the first character of the
first word of a command, then the hash character
and the characters that follow it, up through the
next newline, are treated as a comment and ignored.
The comment character only has significance when it
appears at the beginning of a command.
Se uma lasanha (``#'') aparece numa posição em que o Tcl
esteja esperando o primeiro caracter da primeira palavra
de um comando, então a lasanha e todos os caracteres a
seguir, até o fim da linha, são tratados como um
comentário e ignorados. A lasanha só é interpretada
especialmente, como início de comentário, quando aparece
no início de um comando.
[10] Each character is processed exactly once by the Tcl
interpreter as part of creating the words of a com-
mand. For example, if variable substitution occurs
then no further substitutions are performed on the
value of the variable; the value is inserted into
the word verbatim. If command substitution occurs
then the nested command is processed entirely by
the recursive call to the Tcl interpreter; no sub-
stitutions are performed before making the recur-
sive call and no additional substitutions are per-
formed on the result of the nested script.
Cada caracter é processado exatamente uma vez pelo
interpretador do Tcl durante a fase de obtenção das
palavras de um comando; por exemplo, num trecho onde
ocorre uma substituição de variável nenhuma outra
substituição é aplicada, e o resultado da substituição
de variável é concatenado literalmente à palavra que
está sendo formada. Um trecho em que ocorre uma
substituição de comando é inteiramente processado pela
chamada recursiva ao interpretador do Tcl; nenhuma
substituição é aplicada nesse trecho antes da chamada
recursiva ao interpretador, e nenhuma substituição
adicional é feita sobre o resultado da substituição de
comando nesse trecho.
[11] Substitutions do not affect the word boundaries of
a command. For example, during variable substitu-
tion the entire value of the variable becomes part
of a single word, even if the variable's value con-
tains spaces.
As substituições não afetam as separações entre
palavras. Por exemplo, durante uma substituição de
variável todo o string que corresponde ao valor da
variável se torna parte da palavra em que essa variável
estava, mesmo que o valor da variável contenha espaços.
# Local Variables:
# coding: utf-8-unix
# End: