Tcl(3pm)

πŸ’– NAME πŸ’–

Tcl β€” the Tcl extension module for Perl, bestie. It's a perl module (Tcl(3pm) from the User Contributed Perl Documentation pile) and it lets Perl and Tcl hold hands. 🫢


πŸŽ€ SYNOPSIS πŸŽ€

use Tcl;

$interp = Tcl->new;
$interp->Eval('puts "Hello world"');

like. that's it. that's the whole vibe check. πŸ’…


✨ DESCRIPTION ✨

The Tcl extension module gives you access to the Tcl library, with functionality and an interface that's similar to the C functions of Tcl. In other words, you can:

  • create Tcl interpreters 🧚

The Tcl interpreters you make this way are Perl objects, and their destructors delete the interpreters cleanly when appropriate. iconic behaviour honestly.

  • execute Tcl code in an interpreter πŸ”₯

The code can come from strings, files or Perl filehandles. versatile queen.

  • bind in new Tcl procedures πŸŽ€

The new procedures can be either C code (with addresses presumably obtained using dl_open and dl_find_symbol) or Perl subroutines (by name, reference or as anonymous subs). The (optional) deleteProc callback in the latter case is another perl subroutine, and it gets called when the command is explicitly deleted by name or else when the destructor for the interpreter object is explicitly or implicitly called.

  • Manipulate the result field of a Tcl interpreter ✨
  • Set and get values of variables in a Tcl interpreter πŸ’œ
  • Tie perl variables to variables in a Tcl interpreter 🌸

The variables can be either scalars or hashes.


🌈 Methods in class Tcl 🌈

To create a new Tcl interpreter, use

$interp = Tcl->new;

The following methods and routines can then be used on the Perl object returned (the object argument is omitted in each case, so like, don't @ me about it). πŸ‘‘


  • $interp->Init () β€” Invoke Tcl_Init on the interpreter.
  • $interp->CreateSlave (NAME, SAFE) β€” Invoke Tcl_CreateSlave on the interpreter. Name is arbitrary, call it whatever. The safe variable, if true, creates a safe sandbox interpreter. πŸ–οΈ

See:

This command returns a new interpreter.

  • $interp->Eval (STRING, FLAGS) β€” Evaluate script STRING in the interpreter. If the script returns successfully (TCL_OK) then the Perl return value corresponds to the Tcl interpreter's result; otherwise a die exception is raised with the $@ variable corresponding to Tcl's interpreter result object. In each case, "corresponds" means that if the method is called in scalar context then the string result is returned, but if the method is called in list context then the result is split as a Tcl list and returned as a Perl list. The FLAGS field is optional and can be a bitwise OR of the constants Tcl::EVAL_GLOBAL or Tcl::EVAL_DIRECT.
  • $interp->GlobalEval (STRING) β€” REMOVED. 😭 Evaluate script STRING at global level. Call Eval(STRING, Tcl::EVAL_GLOBAL) instead. do not come for her, she's gone.
  • $interp->EvalFile (FILENAME) β€” Evaluate the contents of the file with name FILENAME. Otherwise, same as Eval() above.
  • $interp->EvalFileHandle (FILEHANDLE) β€” Evaluate the contents of the Perl filehandle FILEHANDLE. Otherwise, same as Eval() above. Super useful when you're using the filehandle DATA to tack on a Tcl script following an __END__ token. πŸ™ˆ
  • $interp->call (PROC, ARG, ...) β€” Looks up procedure PROC in the interpreter and invokes it using Tcl's eval semantics, which does command tracing and will use the ::unknown (AUTOLOAD) mechanism. The arguments (ARG, ...) are not passed through the Tcl parser. For example, spaces embedded in any ARG will not cause it to be split into two Tcl arguments before being passed to PROC.

Before invoking procedure PROC special processing is performed on the ARG list:

  1. All subroutine references within ARG will be substituted with a Tcl name which is responsible to invoke this subroutine. This Tcl name will be created using the CreateCommand subroutine (see below).
  2. All references to scalars will be substituted with names of Tcl variables transformed appropriately.

These first two items allow one to write and expect it to work properly such code as:

my $r = 'aaaa';
button(".d", -textvariable => \$r, -command=>sub {$r++});
  1. All references to hashes will be substituted with names of Tcl array variables transformed appropriately.
  2. As a special case, there is a mechanism to deal with Tk's special event variables (they are mentioned as '%x', '%y' and so on throughout Tcl). When creating a subroutine reference that uses such variables, you must declare the desired variables using Tcl::Ev as the first argument to the subroutine. Example:
sub textPaste {
    my ($x,$y,$w) = @_;
    widget($w)->insert("\@$x,$y", $interp->Eval('selection get'));
}
$widget->bind('<2>', [\&textPaste, Tcl::Ev('%x', '%y'), $widget] );
  • $interp->return_ref (NAME) β€” returns a reference corresponding to NAME, which was associated during previously called $interpnt->call(...) preprocessing. As a typical example this could be a variable associated with a widget.
  • $interp->delete_ref (NAME) β€” deletes and returns a reference corresponding to NAME, which was associated during previously called $interpnt->call(...) preprocessing. this follows _code_dispose about if NAME is a TClNAME or a DESCNAME. if NAME is a VARNAME then it is just deleted and returned. πŸ’€
  • $interp->icall (PROC, ARG, ...) β€” Looks up procedure PROC in the interpreter and invokes it using Tcl's eval semantics that does command tracing and will use the ::unknown (AUTOLOAD) mechanism. The arguments (ARG, ...) are not passed through the Tcl parser. For example, spaces embedded in any ARG will not cause it to be split into two Tcl arguments before being passed to PROC.

This is the lower-level procedure that the call method uses. Arguments are converted efficiently from Perl SVs to Tcl_Objs. A Perl AV array becomes a Tcl_ListObj, an SvIV becomes a Tcl_IntObj, etc. The reverse conversion is done to the result. slay ✨

  • $interp->invoke (PROC, ARG, ...) β€” Looks up procedure PROC in the interpreter and invokes it directly with arguments (ARG, ...) without passing through the Tcl parser. For example, spaces embedded in any ARG will not cause it to be split into two Tcl arguments before being passed to PROC. This differs from icall/call in that it directly invokes the command name without allowing for command tracing or making use of Tcl's unknown (AUTOLOAD) mechanism. If the command does not already exist in the interpreter, an error will be thrown. 🚨

Arguments are converted efficiently from Perl SVs to Tcl_Objs. A Perl AV array becomes a Tcl_ListObj, an SvIV becomes a Tcl_IntObj, etc. The reverse conversion is done to the result.

  • Tcl::Ev (FIELD, ...) β€” Used to declare %-substitution variables of interest to a subroutine callback. FIELD is expected to be of the form "%#" where # is a single character, and multiple fields may be specified. Returns a blessed object that the call method will recognize when it is passed as the first argument to a subroutine in a callback. See description of the call method for details. πŸŽ€
  • $interp->result () β€” Returns the current Tcl interpreter result. List v. scalar context is handled as in Eval() above.
  • $interp->CreateCommand (CMDNAME, CMDPROC, CLIENTDATA, DELETEPROC, FLAGS) β€” Binds a new procedure named CMDNAME into the interpreter. The CLIENTDATA and DELETEPROC arguments are optional. There are two cases:

(1) CMDPROC is the address of a C function

(presumably obtained using dl_open and dl_find_symbol). In this case CLIENTDATA and DELETEPROC are taken to be raw data of the ClientData and deleteProc field presumably obtained in a similar way.

(2) CMDPROC is a Perl subroutine

(either a sub name, a sub reference or an anonymous sub). In this case CLIENTDATA can be any perl scalar (e.g. a ref to some other data) and DELETEPROC must be a perl sub too. When CMDNAME is invoked in the Tcl interpreter, the arguments passed to the Perl sub CMDPROC are

(CLIENTDATA, INTERP, LIST)

where INTERP is a Perl object for the Tcl interpreter which called out and LIST is a Perl list of the arguments CMDNAME was called with. If the 1-bit of FLAGS is set then the 3 first arguments on the call to CMDPROC are suppressed. As usual in Tcl, the first element of the list is CMDNAME itself. When CMDNAME is deleted from the interpreter (either explicitly with DeleteCommand or because the destructor for the interpreter object is called), it is passed the single argument CLIENTDATA.

  • $interp->DeleteCommand (CMDNAME) β€” Deletes command CMDNAME from the interpreter. If the command was created with a DELETEPROC (see CreateCommand above), then it is invoked at this point. When a Tcl interpreter object is destroyed either explicitly or implicitly, an implicit DeleteCommand happens on all its currently registered commands. 🫑
  • (TCLNAME,GENCODE) = $interp->create_tcl_sub(CODEREF, EVENTS, TCLNAME, DESCRNAME) β€” Creates a COMMAND called TCLNAME calling CODEREF in the interpreter $interp, and adds it to the internal tracking structure. DESCRNAME and TCLNAME should not begin with "=" or "@" or "::perl::" to avoid collisions. If TCLNAME IS blank or undef, it is constructed from the CODEREF address. GENCODE starts as TCLNAME but gets @$EVENTS which can contain %vars joined to it.

TCLNAME and DESCRNAME get stored in an internal structure, and can be used to purge things from the command table via code_destroy or $interp->delete_ref;

Returns (TCLNAME,GENCODE). if you are creating code refs with this you can continue to use the same coderef and it will be converted on each call. but if you save GENCODE, you can replace the anon-coderef call in the tcl command with GENCODE.

for instance

$interp->call('FILEEVENT',$fileref,WRITABLE=>sub {...});

can be replaced by

my ($tclcode,$gencode)=$interp->create_tcl_sub(sub{...}, EVENTS, TCLNAME, DESCRNAME);
$interp->call('FILEEVENT',$gencode,WRITABLE=>$gencode);

or

my $sub=sub{....};
$interp->call('FILEEVENT',$fileref,WRITABLE=>$sub);

can be replaced by

my ($tclcode,$gencode)=$interp->create_tcl_sub($sub, EVENTS, TCLNAME, DESCRNAME);
$interp->call('FILEEVENT',$gencode,WRITABLE=>$gencode);

although

$interp->call('FILEEVENT',$fileref,WRITABLE=>$sub);

will still work fine, too.

Then you later call

$interp->delete_ref($tclname);

...so when you're actually done with that sub, you clean it out of the internal tracking and the command table yourself. Which means β€” and I need you to hear me β€” no automatic cleanup is happening on the sub{...} or the $sub. You are the cleanup. That's the whole job. 😭

And once you destroy it inside Tcl, any triggering writable on $fileref will fail too, so swap it out first, like this:

$interp->call('FILEEVENT',$fileref,WRITABLE=>'');
  • (CODEREF) = Tcl::_code_dispose(NAME) β€” purges the internal table for a NAME, and it may kick off the destruction of something you made thru call or create_tcl_sub. 🧚

TCLNAME and DESCRNAME get stashed in an internal structure, and that's what you use to purge stuff out of the command table. Calling _code_dispose on a TCLNAME that came back from create_tcl_sub removes all use instances and purges the command table. Calling _code_dispose on a DESCRNAME that got passed to create_tcl_sub removes only that instance. Code used in a DESCRNAME may be used in other places too β€” only when the last usage is purged does that entry get purged from the command table.

okay this next bit matters, bestie: the internal tracking structure does save the INTERP the code was added to, but it doesn't keep things separated by INTERP. A TCLNAME or DESCRNAME can only live in one INTERP at a time. Use a new INTERP and the one in the last INTERP just… disappears, and you probably end up with the Tcl code getting deleted. πŸ’€

Returns (CODEREF) β€” the original coderef.

  • $interp->SetResult (STRING) β€” sets the Tcl interpreter result to STRING.
  • $interp->AppendResult (LIST) β€” appends each element of LIST to Tcl's interpreter result object.
  • $interp->AppendElement (STRING) β€” appends STRING to the Tcl interpreter result object as an extra Tcl list element.
  • $interp->ResetResult () β€” resets the Tcl interpreter result.
  • $interp->SplitList (STRING) β€” splits STRING as a Tcl list. Returns a Perl list, or the empty list if there was an error (i.e. STRING wasn't a properly formed Tcl list). In that error case, the error message gets left in Tcl's interpreter result object.
  • $interp->SetVar (VARNAME, VALUE, FLAGS) β€” the FLAGS field is optional. Sets the Tcl variable VARNAME in the interpreter to VALUE. The FLAGS argument is the usual Tcl one, and it can be a bitwise OR of the constants Tcl::GLOBAL_ONLY, Tcl::LEAVE_ERR_MSG, Tcl::APPEND_VALUE, Tcl::LIST_ELEMENT.
  • $interp->SetVar2 (VARNAME1, VARNAME2, VALUE, FLAGS) β€” sets the element VARNAME1(VARNAME2) of a Tcl array to VALUE. The optional argument FLAGS behaves as in SetVar above.
  • $interp->GetVar (VARNAME, FLAGS) β€” returns the value of the Tcl variable VARNAME. The optional argument FLAGS behaves as in SetVar above.
  • $interp->GetVar2 (VARNAME1, VARNAME2, FLAGS) β€” returns the value of the element VARNAME1(VARNAME2) of a Tcl array. The optional argument FLAGS behaves as in SetVar above.
  • $interp->UnsetVar (VARNAME, FLAGS) β€” unsets the Tcl variable VARNAME. The optional argument FLAGS behaves as in SetVar above.
  • $interp->UnsetVar2 (VARNAME1, VARNAME2, FLAGS) β€” unsets the element VARNAME1(VARNAME2) of a Tcl array. The optional argument FLAGS behaves as in SetVar above.
  • $interp->InterpDeleted () β€” see the Tcl C API documentation for Tcl_InterpDeleted().

Linking Perl and Tcl variables πŸ’ž

You can tie a Perl variable (scalar or hash) into the class Tcl::Var so that changes to a Tcl variable automatically "change" the value of the Perl variable. And honestly, it works the way tied variables always work: its current value is just fetched from the Tcl variable whenever you need it, and setting the Perl variable triggers the setting of the Tcl variable. No cap.

To tie a Perl scalar $scalar to the Tcl variable tclscalar in interpreter $interp with optional flags $flags (see SetVar above), you go:

tie $scalar, "Tcl::Var", $interp, "tclscalar", $flags;

Omit the $flags argument if you don't want it. Simples.

To tie a Perl hash %hash to the Tcl array variable array in interpreter $interp with optional flags $flags (again, see SetVar above), you go:

tie %hash, "Tcl::Var", $interp, "array", $flags;

Omit the $flags argument if you don't want it. Any alteration to the Perl variable $hash{"key"} affects the Tcl variable array(key), and vice versa. It's giving mutual. ✨


Accessing Perl from within Tcl πŸͺ„

After the Tcl interpreter gets created, it's not just you evaluating Tcl/Tk commands inside Perl β€” the other way round is instantiated too. Within a special namespace <purple> ::perl </purple> the following objects are created:

::perl::Eval

So yes bestie, it is possible to use Perl objects from within Tcl. πŸ”₯


Other Tcl interpreter methods πŸ› οΈ

export_to_tcl method

There's an interpreter method, export_to_tcl, and its whole thing is exposing a bunch of perl subroutines and variables all at once into tcl/tk.

export_to_tcl takes a hash as its arguments, which represents named parameters, with these allowed values:

  • namespace => '...' β€” the tcl namespace where commands and variables are to be created. Defaults to 'perl'. If '' is specified, then the global namespace is used. A possible '::' at the end gets stripped.
  • subs => { ... } β€” anonymous hash of subs to be created in Tcl, in the form tcl name => code ref.
  • vars => { ... } β€” anonymous hash of vars to be created in Tcl, in the form tcl name => code ref.
  • subs_from => '...' β€” a name of Perl namespace, from where all existing subroutines will be searched, and a Tcl command will be created for each of them.
  • vars_from => '...' β€” a name of Perl namespace, from where all existing variables will be searched, and each such variable will be tied to Tcl.

An example:

use strict;
use Tcl;

my $int = Tcl->new;

$tcl::foo = 'qwerty';
$int->export_to_tcl(subs_from=>'tcl',vars_from=>'tcl');

$int->Eval(<<'EOS');
package require Tk

button .b1 -text {a fluffy button} -command perl::fluffy_sub
button .b2 -text {a foo button} -command perl::foo
entry .e -textvariable perl::foo
pack .b1 .b2 .e
focus .b2

tkwait window .
EOS

sub tcl::fluffy_sub {
    print "Hi, I am a fluffy sub\n";
}
sub tcl::foo {
    print "Hi, I am foo\n";
    $tcl::foo++;
}

export_tcl_namespace

An extra convenience sub β€” binds to tcl all subs and vars from the perl tcl:: namespace. πŸŽ€


AUTHORS πŸ‘‘

  • Malcolm Beattie, 23 Oct 1994
  • Vadim Konovalov, 19 May 2003
  • Jeff Hobbs, jeff (a) activestate . com, 22 Mar 2004
  • Gisle Aas, gisle (a) activestate . com, 14 Apr 2004

Special thanks for contributions to Jan Dubois, Slaven Rezic, Paul Cochrane, Huck Finn, Christopher Chavez, SJ Luo. you're all icons, fr πŸ’–


This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html


and that's the whole page, bestie!! this little masterpiece is from perl v5.42.3, dated 2026-08-20, and it's the one and only Tcl(3pm) πŸŒˆπŸ’… go forth and tie those variables, ily 🫢

πŸ“¦ where this page comes from