Tcl/TkApplications
TclCommands
TkCommands
TclLibrary
TkLibrary
Keywords
Tcl8.5.8/Tk8.5.8Documentation
TheinterpreterswhichimplementTclandTk.Thecommandswhichthetclshinterpreterimplements.Theadditionalcommandswhichthewishinterpreterimplements.TheCfunctionswhichaTclextendedCprogrammayuse.TheadditionalCfunctionswhichaTkextendedCprogrammayuse.ThekeywordsfromtheTcl/Tkmanpages.
Copyright©1989-1994TheRegentsoftheUniversityofCaliforniaCopyright©1992-1999KarlLehenbauer&MarkDiekhansCopyright©1992-1999KarlLehenbauerandMarkDiekhansCopyright©1993-1997BellLabsInnovationsforLucentTechnologiesCopyright©1994TheAustralianNationalUniversityCopyright©1994-2000SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1997-2000AjubaSolutionsCopyright©1997-2000ScripticsCorporationCopyright©1998MarkHarrisonCopyright©2000JeffreyHobbsCopyright©2001ActiveStateToolCorpCopyright©2001VincentDarleyCopyright©2001-2004ActiveStateCorporationCopyright©2001-2005KevinB.KennyCopyright©2001-2008DonalK.FellowsCopyright©2002-2008AndreasKupriesCopyright©2003GeorgePetasisCopyright©2003SimonGeardCopyright©2003-2006JoeEnglishCopyright©2006MiguelSofer
Copyright©2006-2007DanielA.SteffenCopyright©2006-2008ActiveStateSoftwareIncCopyright©2008PatThoyts
Tcl8.5.8/Tk8.5.8Documentation>Tcl/TkApplications
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
tclsh wish
Copyright©1991-1994TheRegentsoftheUniversityofCaliforniaCopyright©1994-1996SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJr
Tcl8.5.8/Tk8.5.8Documentation>TclCommands
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
after error lappend platform tcl_findLibraryappend eval lassign platform::shell tcl_startOfNextWordapply exec lindex proc tcl_startOfPreviousWordarray exit linsert puts tcl_wordBreakAfterauto_execok expr list pwd tcl_wordBreakBeforeauto_import fblocked llength re_syntax tcltestauto_load fconfigure load read tclvarsauto_mkindex fcopy lrange refchan tellauto_mkindex_old file lrepeat regexp timeauto_qualify fileevent lreplace registry tmauto_reset filename lreverse regsub tracebgerror flush lsearch rename unknownbinary for lset return unloadbreak foreach lsort SafeBase unsetcatch format mathfunc scan updatecd gets mathop seek uplevelchan glob memory set upvarclock global msgcat socket variableclose history namespace source vwaitconcat http open split whilecontinue if package stringdde incr parray substdict info pid switchencoding interp pkg::create Tcleof join pkg_mkIndex tcl_endOfWord
Copyright©1990-1994TheRegentsoftheUniversityofCaliforniaCopyright©1992-1999KarlLehenbauer&MarkDiekhans
Copyright©1992-1999KarlLehenbauerandMarkDiekhansCopyright©1993-1997BellLabsInnovationsforLucentTechnologiesCopyright©1994-2000SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1998MarkHarrisonCopyright©1998-2000AjubaSolutionsCopyright©1998-2000ScripticsCorporationCopyright©2001-2004ActiveStateCorporationCopyright©2001-2005KevinB.KennyCopyright©2001-2006DonalK.FellowsCopyright©2003GeorgePetasisCopyright©2003SimonGeardCopyright©2004-2008AndreasKupriesCopyright©2006MiguelSoferCopyright©2006-2008ActiveStateSoftwareInc
Tcl8.5.8/Tk8.5.8Documentation>TkCommands
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
bell font options tk_chooseColor tk_textPastebind frame pack tk_chooseDirectory tkerrorbindtags grab panedwindow tk_dialog tkvarsbitmap grid photo tk_focusFollowsMouse tkwaitbutton image place tk_focusNext toplevelcanvas keysyms radiobutton tk_focusPrev ttk::buttoncheckbutton label raise tk_getOpenFile ttk::checkbuttonclipboard labelframe scale tk_getSaveFile ttk::comboboxcolors listbox scrollbar tk_menuSetFocus ttk::entryconsole loadTk selection tk_messageBox ttk::framecursors lower send tk_optionMenu ttk::introdestroy menu spinbox tk_popup ttk::labelentry menubutton text tk_setPalette ttk::labelframeevent message tk tk_textCopy ttk::menubuttonfocus option tk_bisque tk_textCut ttk::notebook
Copyright©1990-1994TheRegentsoftheUniversityofCaliforniaCopyright©1994TheAustralianNationalUniversityCopyright©1994-1997SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1997-2000ScripticsCorporationCopyright©1998-2000AjubaSolutionsCopyright©2000JeffreyHobbsCopyright©2001-2008DonalK.FellowsCopyright©2003ActiveStateCorporationCopyright©2004-2006JoeEnglishCopyright©2006-2007DanielA.SteffenCopyright©2008PatThoyts
Tcl8.5.8/Tk8.5.8Documentation>TclLibrary
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
attemptckalloc Tcl_FSEvalFileattemptckrealloc Tcl_FSEvalFileExckalloc Tcl_FSFileAttrsGetckfree Tcl_FSFileAttrsSetckrealloc Tcl_FSFileAttrStringsTcl_Access Tcl_FSFileSystemInfoTcl_AddErrorInfo Tcl_FSGetCwdTcl_AddObjErrorInfo Tcl_FSGetFileSystemForPathTcl_AlertNotifier Tcl_FSGetInternalRepTcl_Alloc Tcl_FSGetNativePathTcl_AllocStatBuf Tcl_FSGetNormalizedPathTcl_AllowExceptions Tcl_FSGetPathTypeTcl_AppendAllObjTypes Tcl_FSGetTranslatedPathTcl_AppendElement Tcl_FSGetTranslatedStringPathTcl_AppendExportList Tcl_FSJoinPathTcl_AppendFormatToObj Tcl_FSJoinToPathTcl_AppendLimitedToObj Tcl_FSLinkTcl_AppendObjToErrorInfo Tcl_FSListVolumesTcl_AppendObjToObj Tcl_FSLoadFileTcl_AppendPrintfToObj Tcl_FSLstatTcl_AppendResult Tcl_FSMatchInDirectoryTcl_AppendResultVA Tcl_FSMountsChangedTcl_AppendStringsToObj Tcl_FSNewNativePathTcl_AppendStringsToObjVA Tcl_FSOpenFileChannelTcl_AppendToObj Tcl_FSPathSeparatorTcl_AppendUnicodeToObj Tcl_FSRegisterTcl_AppInit Tcl_FSRemoveDirectoryTcl_AsyncCreate Tcl_FSRenameFile
Tcl_AsyncDelete Tcl_FSSplitPathTcl_AsyncInvoke Tcl_FSStatTcl_AsyncMark Tcl_FSUnregisterTcl_AsyncReady Tcl_FSUtimeTcl_AttemptAlloc Tcl_GetAliasTcl_AttemptRealloc Tcl_GetAliasObjTcl_AttemptSetObjLength Tcl_GetAssocDataTcl_BackgroundError Tcl_GetBignumFromObjTcl_Backslash Tcl_GetBooleanTcl_BadChannelOption Tcl_GetBooleanFromObjTcl_CallWhenDeleted Tcl_GetByteArrayFromObjTcl_CancelIdleCall Tcl_GetChannelTcl_ChannelBlockModeProc Tcl_GetChannelBufferSizeTcl_ChannelBuffered Tcl_GetChannelErrorTcl_ChannelClose2Proc Tcl_GetChannelErrorInterpTcl_ChannelCloseProc Tcl_GetChannelHandleTcl_ChannelFlushProc Tcl_GetChannelInstanceDataTcl_ChannelGetHandleProc Tcl_GetChannelModeTcl_ChannelGetOptionProc Tcl_GetChannelNameTcl_ChannelHandlerProc Tcl_GetChannelNamesTcl_ChannelInputProc Tcl_GetChannelNamesExTcl_ChannelName Tcl_GetChannelOptionTcl_ChannelOutputProc Tcl_GetChannelThreadTcl_ChannelSeekProc Tcl_GetChannelTypeTcl_ChannelSetOptionProc Tcl_GetCharLengthTcl_ChannelThreadActionProc Tcl_GetCommandFromObjTcl_ChannelTruncateProc Tcl_GetCommandFullNameTcl_ChannelVersion Tcl_GetCommandInfoTcl_ChannelWatchProc Tcl_GetCommandInfoFromTokenTcl_ChannelWideSeekProc Tcl_GetCommandNameTcl_Chdir Tcl_GetCurrentNamespaceTcl_ClearChannelHandlers Tcl_GetCurrentThreadTcl_Close Tcl_GetCwd
Tcl_CommandComplete Tcl_GetDefaultEncodingDirTcl_CommandTraceInfo Tcl_GetDoubleTcl_Concat Tcl_GetDoubleFromObjTcl_ConcatObj Tcl_GetEncodingTcl_ConditionFinalize Tcl_GetEncodingFromObjTcl_ConditionNotify Tcl_GetEncodingNameTcl_ConditionWait Tcl_GetEncodingNameFromEnvironmentTcl_ConvertCountedElement Tcl_GetEncodingNamesTcl_ConvertElement Tcl_GetEncodingSearchPathTcl_ConvertToType Tcl_GetEnsembleFlagsTcl_CreateAlias Tcl_GetEnsembleMappingDictTcl_CreateAliasObj Tcl_GetEnsembleNamespaceTcl_CreateChannel Tcl_GetEnsembleSubcommandListTcl_CreateChannelHandler Tcl_GetEnsembleUnknownHandlerTcl_CreateCloseHandler Tcl_GetErrnoTcl_CreateCommand Tcl_GetGlobalNamespaceTcl_CreateEncoding Tcl_GetHashKeyTcl_CreateEnsemble Tcl_GetHashValueTcl_CreateEventSource Tcl_GetHostNameTcl_CreateExitHandler Tcl_GetIndexFromObjTcl_CreateFileHandler Tcl_GetIndexFromObjStructTcl_CreateHashEntry Tcl_GetIntTcl_CreateInterp Tcl_GetInterpPathTcl_CreateMathFunc Tcl_GetIntFromObjTcl_CreateNamespace Tcl_GetLongFromObjTcl_CreateObjCommand Tcl_GetMasterTcl_CreateObjTrace Tcl_GetMathFuncInfoTcl_CreateSlave Tcl_GetNameOfExecutableTcl_CreateThread Tcl_GetNamespaceUnknownHandlerTcl_CreateThreadExitHandler Tcl_GetObjResultTcl_CreateTimerHandler Tcl_GetObjTypeTcl_CreateTrace Tcl_GetOpenFileTcl_CutChannel Tcl_GetPathType
Tcl_DecrRefCount Tcl_GetRangeTcl_DeleteAssocData Tcl_GetRegExpFromObjTcl_DeleteChannelHandler Tcl_GetReturnOptionsTcl_DeleteCloseHandler Tcl_GetsTcl_DeleteCommand Tcl_GetServiceModeTcl_DeleteCommandFromToken Tcl_GetSlaveTcl_DeleteEvents Tcl_GetsObjTcl_DeleteEventSource Tcl_GetStackedChannelTcl_DeleteExitHandler Tcl_GetStdChannelTcl_DeleteFileHandler Tcl_GetStringTcl_DeleteHashEntry Tcl_GetStringFromObjTcl_DeleteHashTable Tcl_GetStringResultTcl_DeleteInterp Tcl_GetThreadDataTcl_DeleteNamespace Tcl_GetTimeTcl_DeleteThreadExitHandler Tcl_GetTopChannelTcl_DeleteTimerHandler Tcl_GetUniCharTcl_DeleteTrace Tcl_GetUnicodeTcl_DetachChannel Tcl_GetUnicodeFromObjTcl_DetachPids Tcl_GetVarTcl_DictObjDone Tcl_GetVar2Tcl_DictObjFirst Tcl_GetVar2ExTcl_DictObjGet Tcl_GetVersionTcl_DictObjNext Tcl_GetWideIntFromObjTcl_DictObjPut Tcl_GlobalEvalTcl_DictObjPutKeyList Tcl_GlobalEvalObjTcl_DictObjRemove Tcl_HashStatsTcl_DictObjRemoveKeyList Tcl_HideCommandTcl_DictObjSize Tcl_ImportTcl_DiscardInterpState Tcl_IncrRefCountTcl_DiscardResult Tcl_InitTcl_DontCallWhenDeleted Tcl_InitCustomHashTableTcl_DoOneEvent Tcl_InitHashTableTcl_DoWhenIdle Tcl_InitMemory
Tcl_DStringAppend Tcl_InitNotifierTcl_DStringAppendElement Tcl_InitObjHashTableTcl_DStringEndSublist Tcl_InitStubsTcl_DStringFree Tcl_InputBlockedTcl_DStringGetResult Tcl_InputBufferedTcl_DStringInit Tcl_InterpTcl_DStringLength Tcl_InterpDeletedTcl_DStringResult Tcl_InvalidateStringRepTcl_DStringSetLength Tcl_IsChannelExistingTcl_DStringStartSublist Tcl_IsChannelRegisteredTcl_DStringTrunc Tcl_IsChannelSharedTcl_DStringValue Tcl_IsEnsembleTcl_DumpActiveMemory Tcl_IsSafeTcl_DuplicateObj Tcl_IsSharedTcl_Eof Tcl_IsStandardChannelTcl_ErrnoId Tcl_JoinPathTcl_ErrnoMsg Tcl_JoinThreadTcl_Eval Tcl_LimitAddHandlerTcl_EvalEx Tcl_LimitCheckTcl_EvalFile Tcl_LimitExceededTcl_EvalObjEx Tcl_LimitGetCommandsTcl_EvalObjv Tcl_LimitGetGranularityTcl_EvalTokens Tcl_LimitGetTimeTcl_EvalTokensStandard Tcl_LimitReadyTcl_EventuallyFree Tcl_LimitRemoveHandlerTcl_Exit Tcl_LimitSetCommandsTcl_ExitThread Tcl_LimitSetGranularityTcl_Export Tcl_LimitSetTimeTcl_ExposeCommand Tcl_LimitTypeEnabledTcl_ExprBoolean Tcl_LimitTypeExceededTcl_ExprBooleanObj Tcl_LimitTypeResetTcl_ExprDouble Tcl_LimitTypeSetTcl_ExprDoubleObj Tcl_LinkVar
Tcl_ExprLong Tcl_ListMathFuncsTcl_ExprLongObj Tcl_ListObjAppendElementTcl_ExprObj Tcl_ListObjAppendListTcl_ExprString Tcl_ListObjGetElementsTcl_ExternalToUtf Tcl_ListObjIndexTcl_ExternalToUtfDString Tcl_ListObjLengthTcl_Finalize Tcl_ListObjReplaceTcl_FinalizeNotifier Tcl_LogCommandInfoTcl_FinalizeThread Tcl_MainTcl_FindCommand Tcl_MakeFileChannelTcl_FindEnsemble Tcl_MakeSafeTcl_FindExecutable Tcl_MakeTcpClientChannelTcl_FindHashEntry TCL_MEM_DEBUGTcl_FindNamespace Tcl_MergeTcl_FirstHashEntry Tcl_MutexFinalizeTcl_Flush Tcl_MutexLockTcl_ForgetImport Tcl_MutexUnlockTcl_Format Tcl_NewBignumObjTcl_Free Tcl_NewBooleanObjTcl_FreeEncoding Tcl_NewByteArrayObjTcl_FreeParse Tcl_NewDictObjTcl_FreeResult Tcl_NewDoubleObjTcl_FSAccess Tcl_NewIntObjTcl_FSChdir Tcl_NewListObjTcl_FSConvertToPathType Tcl_NewLongObjTcl_FSCopyDirectory Tcl_NewObjTcl_FSCopyFile Tcl_NewStringObjTcl_FSCreateDirectory Tcl_NewUnicodeObjTcl_FSData Tcl_NewWideIntObjTcl_FSDeleteFile Tcl_NextHashEntryTcl_FSEqualPaths Tcl_NotifyChannel
Copyright©1989-1994TheRegentsoftheUniversityofCalifornia
Copyright©1992-1999KarlLehenbauerandMarkDiekhansCopyright©1994-1998SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1997-2000AjubaSolutionsCopyright©1998-2000ScripticsCorporationCopyright©2001ActiveStateCorporationCopyright©2001ActiveStateToolCorpCopyright©2001VincentDarleyCopyright©2001-2002KevinB.KennyCopyright©2001-2005DonalK.FellowsCopyright©2002-2005AndreasKupries
Tcl8.5.8/Tk8.5.8Documentation>TkLibrary
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
Tk_3DBorderColor Tk_DisplayName Tk_GetReliefFromObjTk_3DBorderGC Tk_DistanceToTextLayout Tk_GetRootCoordsTk_3DHorizontalBevel Tk_Draw3DPolygon Tk_GetScreenMMTk_3DVerticalBevel Tk_Draw3DRectangle Tk_GetScrollInfoTk_AddOption Tk_DrawChars Tk_GetScrollInfoObjTk_Alloc3DBorderFromObj Tk_DrawFocusHighlight Tk_GetSelectionTk_AllocBitmapFromObj Tk_DrawTextLayout Tk_GetUidTk_AllocColorFromObj Tk_Fill3DPolygon Tk_GetUserInactiveTimeTk_AllocCursorFromObj Tk_Fill3DRectangle Tk_GetVisualTk_AllocFontFromObj Tk_FindPhoto Tk_GetVRootGeometryTk_AttachHWND Tk_FontId Tk_GrabTk_Attributes Tk_Free3DBorder Tk_HandleEventTk_BindEvent Tk_Free3DBorderFromObj Tk_HeightTk_CanvasDrawableCoords Tk_FreeBitmap Tk_HWNDToWindowTk_CanvasEventuallyRedraw Tk_FreeBitmapFromObj Tk_IdToWindowTk_CanvasGetCoord Tk_FreeColor Tk_ImageChangedTk_CanvasPsBitmap Tk_FreeColorFromObj Tk_InitTk_CanvasPsColor Tk_FreeColormap Tk_InitConsoleChannelsTk_CanvasPsFont Tk_FreeConfigOptions Tk_InitImageArgsTk_CanvasPsPath Tk_FreeCursor Tk_InitOptionsTk_CanvasPsStipple Tk_FreeCursorFromObj Tk_InitStubsTk_CanvasPsY Tk_FreeFont Tk_InternalBorderBottomTk_CanvasSetStippleOrigin Tk_FreeFontFromObj Tk_InternalBorderLeftTk_CanvasTagsOption Tk_FreeGC Tk_InternalBorderRightTk_CanvasTextInfo Tk_FreeImage Tk_InternalBorderTopTk_CanvasTkwin Tk_FreeOptions Tk_InternAtomTk_CanvasWindowCoords Tk_FreePixmap Tk_InterpTk_Changes Tk_FreeSavedOptions Tk_IntersectTextLayout
Tk_ChangeWindowAttributes Tk_FreeTextLayout Tk_IsContainerTk_CharBbox Tk_FreeXId Tk_IsEmbeddedTk_Class Tk_GeometryRequest Tk_IsMappedTk_ClearSelection Tk_Get3DBorder Tk_IsTopLevelTk_ClipboardAppend Tk_Get3DBorderFromObj Tk_MainTk_ClipboardClear Tk_GetAllBindings Tk_MainLoopTk_CollapseMotionEvents Tk_GetAnchor Tk_MaintainGeometryTk_Colormap Tk_GetAnchorFromObj Tk_MainWindowTk_ComputeTextLayout Tk_GetAtomName Tk_MakeWindowExistTk_ConfigureInfo Tk_GetBinding Tk_ManageGeometryTk_ConfigureValue Tk_GetBitmap Tk_MapWindowTk_ConfigureWidget Tk_GetBitmapFromObj Tk_MeasureCharsTk_ConfigureWindow Tk_GetCapStyle Tk_MinReqHeightTk_CoordsToWindow Tk_GetColor Tk_MinReqWidthTk_CreateBinding Tk_GetColorByValue Tk_MoveResizeWindowTk_CreateBindingTable Tk_GetColorFromObj Tk_MoveToplevelWindowTk_CreateClientMessageHandler Tk_GetColormap Tk_MoveWindowTk_CreateErrorHandler Tk_GetCursor Tk_NameTk_CreateEventHandler Tk_GetCursorFromData Tk_NameOf3DBorderTk_CreateGenericHandler Tk_GetCursorFromObj Tk_NameOfAnchorTk_CreateImageType Tk_GetDash Tk_NameOfBitmapTk_CreateItemType Tk_GetFont Tk_NameOfCapStyleTk_CreateOptionTable Tk_GetFontFromObj Tk_NameOfColorTk_CreatePhotoImageFormat Tk_GetFontMetrics Tk_NameOfCursorTk_CreateSelHandler Tk_GetGC Tk_NameOfFontTk_CreateWindow Tk_GetHINSTANCE Tk_NameOfImageTk_CreateWindowFromPath Tk_GetHWND Tk_NameOfJoinStyleTk_DefineBitmap Tk_GetImage Tk_NameOfJustifyTk_DefineCursor Tk_GetImageMasterData Tk_NameOfReliefTk_DeleteAllBindings Tk_GetItemTypes Tk_NameToWindowTk_DeleteBinding Tk_GetJoinStyle Tk_OffsetTk_DeleteBindingTable Tk_GetJustify Tk_OwnSelectionTk_DeleteClientMessageHandler Tk_GetJustifyFromObj Tk_Parent
Tk_DeleteErrorHandler Tk_GetMMFromObj Tk_ParseArgvTk_DeleteEventHandler Tk_GetNumMainWindows Tk_PathNameTk_DeleteGenericHandler Tk_GetOption Tk_PhotoBlankTk_DeleteImage Tk_GetOptionInfo Tk_PhotoExpandTk_DeleteOptionTable Tk_GetOptionValue Tk_PhotoGetImageTk_DeleteSelHandler Tk_GetPixels Tk_PhotoGetSizeTk_Depth Tk_GetPixelsFromObj Tk_PhotoPutBlockTk_DestroyWindow Tk_GetPixmap Tk_PhotoPutZoomedBlockTk_Display Tk_GetRelief Tk_PhotoSetSize
Copyright©1989-1994TheRegentsoftheUniversityofCaliforniaCopyright©1994TheAustralianNationalUniversityCopyright©1994-1998SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1998-2000ScripticsCorporationCopyright©2000AjubaSolutionsCopyright©2002ActiveStateCorporationCopyright©2003-2004JoeEnglishCopyright©2007ActiveStateSoftwareInc
Tcl8.5.8/Tk8.5.8Documentation>Tcl/TkKeywords
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
Copyright©1989-1994TheRegentsoftheUniversityofCaliforniaCopyright©1992-1999KarlLehenbauer&MarkDiekhansCopyright©1992-1999KarlLehenbauerandMarkDiekhansCopyright©1993-1997BellLabsInnovationsforLucentTechnologiesCopyright©1994TheAustralianNationalUniversityCopyright©1994-2000SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1997-2000AjubaSolutionsCopyright©1997-2000ScripticsCorporationCopyright©1998MarkHarrisonCopyright©2000JeffreyHobbsCopyright©2001ActiveStateToolCorpCopyright©2001VincentDarleyCopyright©2001-2004ActiveStateCorporationCopyright©2001-2005KevinB.KennyCopyright©2001-2008DonalK.FellowsCopyright©2002-2008AndreasKupriesCopyright©2003GeorgePetasisCopyright©2003SimonGeardCopyright©2003-2006JoeEnglishCopyright©2006MiguelSoferCopyright©2006-2007DanielA.SteffenCopyright©2006-2008ActiveStateSoftwareIncCopyright©2008PatThoyts
Tcl/TkApplications
TclCommands
TkCommands
TclLibrary
TkLibrary
Keywords
Tcl8.5.8/Tk8.5.8Documentation
TheinterpreterswhichimplementTclandTk.Thecommandswhichthetclshinterpreterimplements.Theadditionalcommandswhichthewishinterpreterimplements.TheCfunctionswhichaTclextendedCprogrammayuse.TheadditionalCfunctionswhichaTkextendedCprogrammayuse.ThekeywordsfromtheTcl/Tkmanpages.
Copyright©1989-1994TheRegentsoftheUniversityofCaliforniaCopyright©1992-1999KarlLehenbauer&MarkDiekhansCopyright©1992-1999KarlLehenbauerandMarkDiekhansCopyright©1993-1997BellLabsInnovationsforLucentTechnologiesCopyright©1994TheAustralianNationalUniversityCopyright©1994-2000SunMicrosystems,IncCopyright©1995-1997RogerE.CritchlowJrCopyright©1997-2000AjubaSolutionsCopyright©1997-2000ScripticsCorporationCopyright©1998MarkHarrisonCopyright©2000JeffreyHobbsCopyright©2001ActiveStateToolCorpCopyright©2001VincentDarleyCopyright©2001-2004ActiveStateCorporationCopyright©2001-2005KevinB.KennyCopyright©2001-2008DonalK.FellowsCopyright©2002-2008AndreasKupriesCopyright©2003GeorgePetasisCopyright©2003SimonGeardCopyright©2003-2006JoeEnglishCopyright©2006MiguelSofer
Copyright©2006-2007DanielA.SteffenCopyright©2006-2008ActiveStateSoftwareIncCopyright©2008PatThoyts
Tcl8.5.8/Tk8.5.8Documentation>UserCmd>tclsh
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEtclsh-SimpleshellcontainingTclinterpreter
SYNOPSISDESCRIPTIONSCRIPTFILESVARIABLES
argcargvargv0tcl_interactive
PROMPTSSTANDARDCHANNELSSEEALSOKEYWORDS
NAME
tclsh-SimpleshellcontainingTclinterpreter
SYNOPSIS
tclsh?-encodingname??fileNameargarg...?
DESCRIPTION
Tclshisashell-likeapplicationthatreadsTclcommandsfromitsstandardinputorfromafileandevaluatesthem.Ifinvokedwithnoargumentsthenitrunsinteractively,readingTclcommandsfromstandardinputandprintingcommandresultsanderrormessagestostandardoutput.Itrunsuntiltheexitcommandisinvokedoruntilitreachesend-of-fileonitsstandardinput.Ifthereexistsafile.tclshrc(ortclshrc.tclontheWindowsplatforms)inthehomedirectoryoftheuser,
interactivetclshevaluatesthefileasaTclscriptjustbeforereadingthefirstcommandfromstandardinput.
SCRIPTFILES
Iftclshisinvokedwithargumentsthenthefirstfewargumentsspecifythenameofascriptfile,and,optionally,theencodingofthetextdatastoredinthatscriptfile.Anyadditionalargumentsaremadeavailabletothescriptasvariables(seebelow).InsteadofreadingcommandsfromstandardinputtclshwillreadTclcommandsfromthenamedfile;tclshwillexitwhenitreachestheendofthefile.Theendofthefilemaybemarkedeitherbythephysicalendofthemedium,orbythecharacter,“\032”(“\u001a”,control-Z).Ifthischaracterispresentinthefile,thetclshapplicationwillreadtextuptobutnotincludingthecharacter.Anapplicationthatrequiresthischaracterinthefilemaysafelyencodeitas“\032”,“\x1a”,or“\u001a”;ormaygenerateitbyuseofcommandssuchasformatorbinary.Thereisnoautomaticevaluationof.tclshrcwhenthenameofascriptfileispresentedonthetclshcommandline,butthescriptfilecanalwayssourceitifdesired.
IfyoucreateaTclscriptinafilewhosefirstlineis
#!/usr/local/bin/tclsh
thenyoucaninvokethescriptfiledirectlyfromyourshellifyoumarkthefileasexecutable.Thisassumesthattclshhasbeeninstalledinthedefaultlocationin/usr/local/bin;ifitisinstalledsomewhereelsethenyouwillhavetomodifytheabovelinetomatch.ManyUNIXsystemsdonotallowthe#!linetoexceedabout30charactersinlength,sobesurethatthetclshexecutablecanbeaccessedwithashortfilename.
Anevenbetterapproachistostartyourscriptfileswiththefollowingthreelines:
#!/bin/sh
#thenextlinerestartsusingtclsh\exectclsh"$0""$@"
Thisapproachhasthreeadvantagesovertheapproachinthepreviousparagraph.First,thelocationofthetclshbinarydoesnothavetobehard-wiredintothescript:itcanbeanywhereinyourshellsearchpath.Second,itgetsaroundthe30-characterfilenamelimitinthepreviousapproach.Third,thisapproachwillworkeveniftclshisitselfashellscript(thisisdoneonsomesystemsinordertohandlemultiplearchitecturesoroperatingsystems:thetclshscriptselectsoneofseveralbinariestorun).Thethreelinescausebothshandtclshtoprocessthescript,buttheexecisonlyexecutedbysh.shprocessesthescriptfirst;ittreatsthesecondlineasacommentandexecutesthethirdline.Theexecstatementcausetheshelltostopprocessingandinsteadtostartuptclshtoreprocesstheentirescript.Whentclshstartsup,ittreatsallthreelinesascomments,sincethebackslashattheendofthesecondlinecausesthethirdlinetobetreatedaspartofthecommentonthesecondline.
Youshouldnotethatitisalsocommonpracticetoinstalltclshwithitsversionnumberaspartofthename.ThishastheadvantageofallowingmultipleversionsofTcltoexistonthesamesystematonce,butalsothedisadvantageofmakingithardertowritescriptsthatstartupuniformlyacrossdifferentversionsofTcl.
VARIABLES
TclshsetsthefollowingTclvariables:
argcContainsacountofthenumberofargarguments(0ifnone),notincludingthenameofthescriptfile.
argvContainsaTcllistwhoseelementsaretheargarguments,inorder,oranemptystringiftherearenoargarguments.
argv0ContainsfileNameifitwasspecified.Otherwise,containsthenamebywhichtclshwasinvoked.
tcl_interactiveContains1iftclshisrunninginteractively(nofileNamewasspecifiedandstandardinputisaterminal-likedevice),0otherwise.
PROMPTS
Whentclshisinvokedinteractivelyitnormallypromptsforeachcommandwith“%”.Youcanchangethepromptbysettingthevariablestcl_prompt1andtcl_prompt2.Ifvariabletcl_prompt1existsthenitmustconsistofaTclscripttooutputaprompt;insteadofoutputtingaprompttclshwillevaluatethescriptintcl_prompt1.Thevariabletcl_prompt2isusedinasimilarwaywhenanewlineistypedbutthecurrentcommandisnotyetcomplete;iftcl_prompt2isnotsetthennopromptisoutputforincompletecommands.
STANDARDCHANNELS
SeeTcl_StandardChannelsformoreexplanations.
SEEALSO
encoding,fconfigure,tclvars
KEYWORDS
argument,interpreter,prompt,scriptfile,shell
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>UserCmd>wish
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEwish-Simplewindowingshell
SYNOPSISOPTIONS
-encodingname-colormapnew-displaydisplay-geometrygeometry-namename-sync-useid-visualvisual--
DESCRIPTIONOPTIONPROCESSINGAPPLICATIONNAMEANDCLASSVARIABLES
argcargvargv0geometrytcl_interactive
SCRIPTFILESPROMPTSKEYWORDS
NAME
wish-Simplewindowingshell
SYNOPSIS
wish?-encodingname??fileNameargarg...?
OPTIONS
-encodingnameSpecifiestheencodingofthetextstoredinfileName.ThisoptionisonlyrecognizedpriortothefileNameargument.
-colormapnewSpecifiesthatthewindowshouldhaveanewprivatecolormapinsteadofusingthedefaultcolormapforthescreen.
-displaydisplayDisplay(andscreen)onwhichtodisplaywindow.
-geometrygeometryInitialgeometrytouseforwindow.Ifthisoptionisspecified,itsvalueisstoredinthegeometryglobalvariableoftheapplication'sTclinterpreter.
-namenameUsenameasthetitletobedisplayedinthewindow,andasthenameoftheinterpreterforsendcommands.
-syncExecuteallXservercommandssynchronously,sothaterrorsarereportedimmediately.Thiswillresultinmuchslowerexecution,butitisusefulfordebugging.
-useidSpecifiesthatthemainwindowfortheapplicationistobeembeddedinthewindowwhoseidentifierisid,insteadofbeingcreatedasanindependenttoplevelwindow.Idmustbespecifiedinthesamewayasthevalueforthe-useoptionfortoplevelwidgets(i.e.ithasaformlikethatreturnedbythewinfoidcommand).
NotethatonsomeplatformsthiswillonlyworkcorrectlyifidreferstoaTkframeortoplevelthathasits-containeroptionenabled.
-visualvisualSpecifiesthevisualtouseforthewindow.VisualmayhaveanyoftheformssupportedbytheTk_GetVisualprocedure.
--Passallremainingargumentsthroughtothescript'sargvvariablewithoutinterpretingthem.Thisprovidesamechanismforpassingargumentssuchas-nametoascriptinsteadofhavingwishinterpretthem.
DESCRIPTION
WishisasimpleprogramconsistingoftheTclcommandlanguage,theTktoolkit,andamainprogramthatreadscommandsfromstandardinputorfromafile.ItcreatesamainwindowandthenprocessesTclcommands.Ifwishisinvokedwitharguments,thenthefirstfewarguments,?-encodingname??fileName?specifythenameofascriptfile,and,optionally,theencodingofthetextdatastoredinthatscriptfile.AvalueforfileNameisrecognizediftheappropriateargumentdoesnotstartwith“-”.
Iftherearenoarguments,ortheargumentsdonotspecifyafileName,thenwishreadsTclcommandsinteractivelyfromstandardinput.Itwillcontinueprocessingcommandsuntilallwindowshavebeendeletedoruntilend-of-fileisreachedonstandardinput.Ifthereexistsafile“.wishrc”inthehomedirectoryoftheuser,wishevaluatesthefileasaTclscriptjustbeforereadingthefirstcommandfromstandardinput.
IfargumentstowishdospecifyafileName,thenfileNameistreatedasthenameofascriptfile.WishwillevaluatethescriptinfileName(whichpresumablycreatesauserinterface),thenitwillrespondtoeventsuntilallwindowshavebeendeleted.Commandswillnotbereadfromstandardinput.Thereisnoautomaticevaluationof“.wishrc”whenthenameofascriptfileispresentedonthewishcommandline,butthescriptfilecanalwayssourceitifdesired.
NotethatonWindows,thewishversion.exeprogramvariesfromthetclshversion.exeprograminanadditionalimportantway:itdoesnot
connecttoastandardWindowsconsoleandisinsteadawindowedprogram.Becauseofthis,itadditionallyprovidesaccesstoitsownconsolecommand.
OPTIONPROCESSING
Wishautomaticallyprocessesallofthecommand-lineoptionsdescribedintheOPTIONSsummaryabove.Anyothercommand-lineargumentsbesidesthesearepassedthroughtotheapplicationusingtheargcandargvvariablesdescribedlater.
APPLICATIONNAMEANDCLASS
Thenameoftheapplication,whichisusedforpurposessuchassendcommands,istakenfromthe-nameoption,ifitisspecified;otherwiseitistakenfromfileName,ifitisspecified,orfromthecommandnamebywhichwishwasinvoked.Inthelasttwocases,ifthenamecontainsa“/”character,thenonlythecharactersafterthelastslashareusedastheapplicationname.
Theclassoftheapplication,whichisusedforpurposessuchasspecifyingoptionswithaRESOURCE_MANAGERpropertyor.Xdefaultsfile,isthesameasitsnameexceptthatthefirstletteriscapitalized.
VARIABLES
WishsetsthefollowingTclvariables:
argcContainsacountofthenumberofargarguments(0ifnone),notincludingtheoptionsdescribedabove.
argvContainsaTcllistwhoseelementsaretheargargumentsthatfollowa--optionordonotmatchanyoftheoptionsdescribedinOPTIONSabove,inorder,oranemptystringiftherearenosucharguments.
argv0ContainsfileNameifitwasspecified.Otherwise,containsthenamebywhichwishwasinvoked.
geometryIfthe-geometryoptionisspecified,wishcopiesitsvalueintothisvariable.IfthevariablestillexistsafterfileNamehasbeenevaluated,wishusesthevalueofthevariableinawmgeometrycommandtosetthemainwindow'sgeometry.
tcl_interactiveContains1ifwishisreadingcommandsinteractively(fileNamewasnotspecifiedandstandardinputisaterminal-likedevice),0otherwise.
SCRIPTFILES
IfyoucreateaTclscriptinafilewhosefirstlineis
#!/usr/local/bin/wish
thenyoucaninvokethescriptfiledirectlyfromyourshellifyoumarkitasexecutable.Thisassumesthatwishhasbeeninstalledinthedefaultlocationin/usr/local/bin;ifitisinstalledsomewhereelsethenyouwillhavetomodifytheabovelinetomatch.ManyUNIXsystemsdonotallowthe#!linetoexceedabout30charactersinlength,sobesurethatthewishexecutablecanbeaccessedwithashortfilename.
Anevenbetterapproachistostartyourscriptfileswiththefollowingthreelines:
#!/bin/sh#thenextlinerestartsusingwish\execwish"$0""$@"
Thisapproachhasthreeadvantagesovertheapproachinthepreviousparagraph.First,thelocationofthewishbinarydoesnothavetobehard-wiredintothescript:itcanbeanywhereinyourshellsearchpath.Second,itgetsaroundthe30-characterfilenamelimitinthepreviousapproach.Third,thisapproachwillworkevenifwishisitselfashellscript(thisisdoneonsomesystemsinordertohandlemultiplearchitecturesoroperatingsystems:thewishscriptselectsoneofseveralbinariestorun).Thethreelinescausebothshandwishtoprocessthescript,buttheexecisonlyexecutedbysh.shprocessesthescriptfirst;ittreatsthesecondlineasacommentandexecutesthethirdline.Theexecstatementcausetheshelltostopprocessingandinsteadtostartupwishtoreprocesstheentirescript.Whenwishstartsup,ittreatsallthreelinesascomments,sincethebackslashattheendofthesecondlinecausesthethirdlinetobetreatedaspartofthecommentonthesecondline.
Theendofascriptfilemaybemarkedeitherbythephysicalendofthemedium,orbythecharacter,“\032”(“\u001a”,control-Z).Ifthischaracterispresentinthefile,thewishapplicationwillreadtextuptobutnotincludingthecharacter.Anapplicationthatrequiresthischaracterinthefilemayencodeitas“\032”,“\x1a”,or“\u001a”;ormaygenerateitbyuseofcommandssuchasformatorbinary.
PROMPTS
Whenwishisinvokedinteractivelyitnormallypromptsforeachcommandwith“%”.Youcanchangethepromptbysettingthevariablestcl_prompt1andtcl_prompt2.Ifvariabletcl_prompt1existsthenitmustconsistofaTclscripttooutputaprompt;insteadofoutputtingapromptwishwillevaluatethescriptintcl_prompt1.Thevariabletcl_prompt2isusedinasimilarwaywhenanewlineistypedbutthecurrentcommandisnotyetcomplete;iftcl_prompt2isnotsetthennopromptisoutputforincompletecommands.
KEYWORDS
shell,toolkit
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1991-1994TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>after
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEafter-Executeacommandafteratimedelay
SYNOPSISDESCRIPTION
aftermsafterms?scriptscriptscript...?aftercancelidaftercancelscriptscript...afteridlescript?scriptscript...?afterinfo?id?
EXAMPLESSEEALSOKEYWORDS
NAME
after-Executeacommandafteratimedelay
SYNOPSIS
aftermsafterms?scriptscriptscript...?aftercancelidaftercancelscriptscriptscript...afteridle?scriptscriptscript...?afterinfo?id?
DESCRIPTION
Thiscommandisusedtodelayexecutionoftheprogramortoexecuteacommandinbackgroundsometimeinthefuture.Ithasseveralforms,dependingonthefirstargumenttothecommand:
aftermsMsmustbeanintegergivingatimeinmilliseconds.Thecommandsleepsformsmillisecondsandthenreturns.Whilethecommandissleepingtheapplicationdoesnotrespondtoevents.
afterms?scriptscriptscript...?Inthisformthecommandreturnsimmediately,butitarrangesforaTclcommandtobeexecutedmsmillisecondslaterasaneventhandler.Thecommandwillbeexecutedexactlyonce,atthegiventime.Thedelayedcommandisformedbyconcatenatingallthescriptargumentsinthesamefashionastheconcatcommand.Thecommandwillbeexecutedatgloballevel(outsidethecontextofanyTclprocedure).Ifanerroroccurswhileexecutingthedelayedcommandthenthebackgrounderrorwillbereportedbythecommandregisteredwithinterpbgerror.Theaftercommandreturnsanidentifierthatcanbeusedtocancelthedelayedcommandusingaftercancel.
aftercancelidCancelstheexecutionofadelayedcommandthatwaspreviouslyscheduled.Idindicateswhichcommandshouldbecanceled;itmusthavebeenthereturnvaluefromapreviousaftercommand.Ifthecommandgivenbyidhasalreadybeenexecutedthentheaftercancelcommandhasnoeffect.
aftercancelscriptscript...Thiscommandalsocancelstheexecutionofadelayedcommand.Thescriptargumentsareconcatenatedtogetherwithspaceseparators(justasintheconcatcommand).Ifthereisapendingcommandthatmatchesthestring,itiscancelledandwillneverbeexecuted;ifnosuchcommandiscurrentlypendingthentheaftercancelcommandhasnoeffect.
afteridlescript?scriptscript...?Concatenatesthescriptargumentstogetherwithspaceseparators(justasintheconcatcommand),andarrangesfortheresultingscripttobeevaluatedlaterasanidlecallback.Thescriptwillberunexactlyonce,thenexttimetheeventloopisenteredandthere
arenoeventstoprocess.Thecommandreturnsanidentifierthatcanbeusedtocancelthedelayedcommandusingaftercancel.Ifanerroroccurswhileexecutingthescriptthenthebackgrounderrorwillbereportedbythecommandregisteredwithinterpbgerror.
afterinfo?id?Thiscommandreturnsinformationaboutexistingeventhandlers.Ifnoidargumentissupplied,thecommandreturnsalistoftheidentifiersforallexistingeventhandlerscreatedbytheaftercommandforthisinterpreter.Ifidissupplied,itspecifiesanexistinghandler;idmusthavebeenthereturnvaluefromsomepreviouscalltoafteranditmustnothavetriggeredyetorbeencancelled.Inthiscasethecommandreturnsalistwithtwoelements.Thefirstelementofthelististhescriptassociatedwithid,andthesecondelementiseitheridleortimertoindicatewhatkindofeventhandleritis.
Theaftermsandafteridleformsofthecommandassumethattheapplicationiseventdriven:thedelayedcommandswillnotbeexecutedunlesstheapplicationenterstheeventloop.Inapplicationsthatarenotnormallyevent-driven,suchastclsh,theeventloopcanbeenteredwiththevwaitandupdatecommands.
EXAMPLES
ThisdefinesacommandtomakeTcldonothingatallforNseconds:
procsleep{N}{after[expr{int($N*1000)}]}
Thisarrangesforthecommandwake_uptoberunineighthours(providingtheeventloopisactiveatthattime):
after[expr{1000*60*60*8}]wake_up
Thefollowingcommandcanbeusedtodolong-runningcalculations(asrepresentedhereby::my_calc::one_step,whichisassumedtoreturnabooleanindicatingwhetheranotherstepshouldbeperformed)inastep-by-stepfashion,thoughthecalculationitselfneedstobearrangedsoitcanworkstep-wise.Thistechniqueisextracarefultoensurethattheeventloopisnotstarvedbythereschedulingofprocessingsteps(arrangingforthenextsteptobedoneusinganalready-triggeredtimereventonlywhentheeventqueuehasbeendrained)andisusefulwhenyouwanttoensurethataTkGUIremainsresponsiveduringaslowtask.
procdoOneStep{}{if{[::my_calc::one_step]}{afteridle[listafter0doOneStep]}}doOneStep
SEEALSO
concat,interp,update,vwait
KEYWORDS
cancel,delay,idlecallback,sleep,time
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1990-1994TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>error
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
error-Generateanerror
SYNOPSIS
errormessage?info??code?
DESCRIPTION
ReturnsaTCL_ERRORcode,whichcausescommandinterpretationtobeunwound.Messageisastringthatisreturnedtotheapplicationtoindicatewhatwentwrong.
The-errorinforeturnoptionofaninterpreterisusedtoaccumulateastacktraceofwhatwasinprogresswhenanerroroccurred;asnestedcommandsunwind,theTclinterpreteraddsinformationtothe-errorinforeturnoption.Iftheinfoargumentispresent,itisusedtoinitializethe-errorinforeturnoptionsandthefirstincrementofunwindinformationwillnotbeaddedbytheTclinterpreter.Inotherwords,thecommandcontainingtheerrorcommandwillnotappearinthestacktrace;initsplacewillbeinfo.Historically,thisfeaturehadbeenmostusefulinconjunctionwiththecatchcommand:ifacaughterrorcannotbehandledsuccessfully,infocanbeusedtoreturnastacktracereflectingtheoriginalpointofoccurrenceoftheerror:
catch{...}errMsgsetsavedInfo$::errorInfo...error$errMsg$savedInfo
WhenworkingwithTcl8.5orlater,thefollowingcodeshouldbeusedinstead:
catch{...}errMsgoptions...return-options$options$errMsg
Ifthecodeargumentispresent,thenitsvalueisstoredinthe-errorcodereturnoption.The-errorcodereturnoptionisintendedtoholdamachine-readabledescriptionoftheerrorincaseswheresuchinformationisavailable;seethereturnmanualpageforinformationontheproperformatforthisoption'svalue.
EXAMPLE
Generateanerrorifabasicmathematicaloperationfails:
if{1+2!=3}{error"somethingisverywrongwithaddition"}
SEEALSO
catch,return
KEYWORDS
error
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>lappend
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
lappend-Appendlistelementsontoavariable
SYNOPSIS
lappendvarName?valuevaluevalue...?
DESCRIPTION
ThiscommandtreatsthevariablegivenbyvarNameasalistandappendseachofthevalueargumentstothatlistasaseparateelement,withspacesbetweenelements.IfvarNamedoesnotexist,itiscreatedasalistwithelementsgivenbythevaluearguments.Lappendissimilartoappendexceptthatthevaluesareappendedaslistelementsratherthanrawtext.Thiscommandprovidesarelativelyefficientwaytobuilduplargelists.Forexample,“lappenda$b”ismuchmoreefficientthan“seta[concat$a[list$b]]”when$aislong.
EXAMPLE
Usinglappendtobuildupalistofnumbers.
%setvar11%lappendvar212%lappendvar34512345
SEEALSO
list,lindex,linsert,llength,lset,lsort,lrange
KEYWORDS
append,element,list,variable
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.Copyright©2001KevinB.Kenny.Allrightsreserved.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>platform
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
platform-Systemidentificationsupportcodeandutilities
SYNOPSIS
packagerequireplatform?1.0.4?platform::genericplatform::identifyplatform::patternsidentifier
DESCRIPTION
TheplatformpackageprovidesseveralutilitycommandsusefulfortheidentificationofthearchitectureofamachinerunningTcl.
WhilstTclprovidesthetcl_platformarrayforidentifyingthecurrentarchitecture(inparticular,theplatformandmachineelements)thisisnotalwayssufficient.Thisisbecause(onUnixmachines)tcl_platformreflectsthevaluesreturnedbytheunamecommandandthesearenotstandardizedacrossplatformsandarchitectures.Inaddition,onatleastoneplatform(AIX)thetcl_platform(machine)containstheCPUserialnumber.
Consequently,individualapplicationsneedtomanipulatethevaluesintcl_platform(alongwiththeoutputofsystemspecificutilities)-whichisbothinconvenientfordevelopers,andintroducesthepotentialforinconsistenciesinidentifyingarchitecturesandinnamingconventions.
Theplatformpackagepreventssuchfragmentation-i.e.,itestablishesastandardnamingconventionforarchitecturesrunningTclandmakesitmoreconvenientfordeveloperstoidentifythecurrentarchitecturea
Tclprogramisrunningon.
COMMANDS
platform::identifyThiscommandreturnsanidentifierdescribingtheplatformtheTclcoreisrunningon.ThereturnedidentifierhasthegeneralformatOS-CPU.TheOSpartoftheidentifiermaycontaindetailslikekernelversion,libcversion,etc.,andthisinformationmaycontaindashesaswell.TheCPUpartwillnotcontaindashes,makingtheprecedingdashthelastdashintheresult.
platform::genericThiscommandreturnsasimplifiedidentifierdescribingtheplatformtheTclcoreisrunningon.Incontrasttoplatform::identifyitleavesoutdetailslikekernelversion,libcversion,etc.ThereturnedidentifierhasthegeneralformatOS-CPU.
platform::patternsidentifierThiscommandtakesanidentifierasreturnedbyplatform::identifyandreturnsalistofidentifiersdescribingcompatiblearchitectures.
KEYWORDS
operatingsystem,cpuarchitecture,platform,architecture
Copyright©1995-1997RogerE.CritchlowJr.Copyright©2006ActiveStateSoftwareInc
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>library
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEauto_execok,auto_import,auto_load,auto_mkindex,auto_mkindex_old,auto_qualify,auto_reset,tcl_findLibrary,parray,tcl_endOfWord,tcl_startOfNextWord,tcl_startOfPreviousWord,tcl_wordBreakAfter,tcl_wordBreakBefore-standardlibraryofTclprocedures
SYNOPSISINTRODUCTIONCOMMANDPROCEDURES
auto_execokcmdauto_importpatternauto_loadcmdauto_mkindexdirpatternpattern...auto_resetauto_qualifycommandnamespacetcl_findLibrarybasenameversionpatchinitScriptenVarNamevarNameparrayarrayNametcl_endOfWordstrstarttcl_startOfNextWordstrstarttcl_startOfPreviousWordstrstarttcl_wordBreakAfterstrstarttcl_wordBreakBeforestrstart
VARIABLESauto_execsauto_indexauto_noexecauto_noloadauto_pathenv(TCL_LIBRARY)env(TCLLIBPATH)
tcl_nonwordcharstcl_wordchars
SEEALSOKEYWORDS
NAME
auto_execok,auto_import,auto_load,auto_mkindex,auto_mkindex_old,auto_qualify,auto_reset,tcl_findLibrary,parray,tcl_endOfWord,tcl_startOfNextWord,tcl_startOfPreviousWord,tcl_wordBreakAfter,tcl_wordBreakBefore-standardlibraryofTclprocedures
SYNOPSIS
auto_execokcmdauto_importpatternauto_loadcmdauto_mkindexdirpatternpattern...auto_mkindex_olddirpatternpattern...auto_qualifycommandnamespaceauto_resettcl_findLibrarybasenameversionpatchinitScriptenVarNamevarNameparrayarrayNametcl_endOfWordstrstarttcl_startOfNextWordstrstarttcl_startOfPreviousWordstrstarttcl_wordBreakAfterstrstarttcl_wordBreakBeforestrstart
INTRODUCTION
TclincludesalibraryofTclproceduresforcommonly-neededfunctions.TheproceduresdefinedintheTcllibraryaregenericonessuitableforusebymanydifferentapplications.ThelocationoftheTcllibraryisreturnedbytheinfolibrarycommand.InadditiontotheTcllibrary,eachapplicationwillnormallyhaveitsownlibraryofsupportprocedures
aswell;thelocationofthislibraryisnormallygivenbythevalueofthe$app_libraryglobalvariable,whereappisthenameoftheapplication.Forexample,thelocationoftheTklibraryiskeptinthevariable$tk_library.
ToaccesstheproceduresintheTcllibrary,anapplicationshouldsourcethefileinit.tclinthelibrary,forexamplewiththeTclcommand
source[filejoin[infolibrary]init.tcl]
IfthelibraryprocedureTcl_Initisinvokedfromanapplication'sTcl_AppInitprocedure,thishappensautomatically.Thecodeininit.tclwilldefinetheunknownprocedureandarrangefortheotherprocedurestobeloadedon-demandusingtheauto-loadmechanismdefinedbelow.
COMMANDPROCEDURES
ThefollowingproceduresareprovidedintheTcllibrary:
auto_execokcmdDetermineswhetherthereisanexecutablefileorshellbuiltinbythenamecmd.Ifso,itreturnsalistofargumentstobepassedtoexectoexecutetheexecutablefileorshellbuiltinnamedbycmd.Ifnot,itreturnsanemptystring.Thiscommandexaminesthedirectoriesinthecurrentsearchpath(givenbythePATHenvironmentvariable)initssearchforanexecutablefilenamedcmd.OnWindowsplatforms,thesearchisexpandedwiththesamedirectoriesandfileextensionsasusedbyexec.Auto_execokremembersinformationaboutprevioussearchesinanarraynamedauto_execs;thisavoidsthepathsearchinfuturecallsforthesamecmd.Thecommandauto_resetmaybeusedtoforceauto_execoktoforgetitscachedinformation.
auto_importpatternAuto_importisinvokedduringnamespaceimporttoseeifthe
importedcommandsspecifiedbypatternresideinanautoloadedlibrary.Ifso,thecommandsareloadedsothattheywillbeavailabletotheinterpreterforcreatingtheimportlinks.Ifthecommandsdonotresideinanautoloadedlibrary,auto_importdoesnothing.Thepatternmatchingisperformedaccordingtothematchingrulesofnamespaceimport.
auto_loadcmdThiscommandattemptstoloadthedefinitionforaTclcommandnamedcmd.Todothis,itsearchesanauto-loadpath,whichisalistofoneormoredirectories.Theauto-loadpathisgivenbytheglobalvariable$auto_pathifitexists.Ifthereisno$auto_pathvariable,thentheTCLLIBPATHenvironmentvariableisused,ifitexists.Otherwisetheauto-loadpathconsistsofjusttheTcllibrarydirectory.Withineachdirectoryintheauto-loadpaththeremustbeafiletclIndexthatdescribesoneormorecommandsdefinedinthatdirectoryandascripttoevaluatetoloadeachofthecommands.ThetclIndexfileshouldbegeneratedwiththeauto_mkindexcommand.Ifcmdisfoundinanindexfile,thentheappropriatescriptisevaluatedtocreatethecommand.Theauto_loadcommandreturns1ifcmdwassuccessfullycreated.Thecommandreturns0iftherewasnoindexentryforcmdorifthescriptdidnotactuallydefinecmd(e.g.becauseindexinformationisoutofdate).Ifanerroroccurswhileprocessingthescript,thenthaterrorisreturned.Auto_loadonlyreadstheindexinformationonceandsavesitinthearrayauto_index;futurecallstoauto_loadcheckforcmdinthearrayratherthanre-readingtheindexfiles.Thecachedindexinformationmaybedeletedwiththecommandauto_reset.Thiswillforcethenextauto_loadcommandtoreloadtheindexdatabasefromdisk.
auto_mkindexdirpatternpattern...Generatesanindexsuitableforusebyauto_load.Thecommandsearchesdirforallfileswhosenamesmatchanyofthepatternarguments(matchingisdonewiththeglobcommand),generatesanindexofalltheTclcommandproceduresdefinedinallthematchingfiles,andstorestheindexinformationinafilenamed
tclIndexindir.Ifnopatternisgivenapatternof*.tclwillbeassumed.Forexample,thecommand
auto_mkindexfoo*.tcl
willreadallthe.tclfilesinsubdirectoryfooandgenerateanewindexfilefoo/tclIndex.
Auto_mkindexparsestheTclscriptsbysourcingthemintoaslaveinterpreterandmonitoringtheprocandnamespacecommandsthatareexecuted.Extensionscanusethe(undocumented)auto_mkindex_parserpackagetoregisterothercommandsthatcancontributetotheauto_loadindex.Youwillhavetoreadthroughauto.tcltoseehowthisworks.
Auto_mkindex_oldparsestheTclscriptsinarelativelyunsophisticatedway:ifanylinecontainsthewordprocasitsfirstcharactersthenitisassumedtobeaproceduredefinitionandthenextwordofthelineistakenastheprocedure'sname.Proceduredefinitionsthatdonotappearinthisway(e.g.theyhavespacesbeforetheproc)willnotbeindexed.Ifyourscriptcontains“dangerous”code,suchasglobalinitializationcodeorprocedurenameswithspecialcharacterslike$,*,[or],youaresaferusingauto_mkindex_old.
auto_resetDestroysalltheinformationcachedbyauto_execokandauto_load.Thisinformationwillbere-readfromdiskthenexttimeitisneeded.Auto_resetalsodeletesanyprocedureslistedintheauto-loadindex,sothatfreshcopiesofthemwillbeloadedthenexttimethattheyareused.
auto_qualifycommandnamespaceComputesalistoffullyqualifiednamesforcommand.ThislistmirrorsthepathastandardTclinterpreterfollowsforcommandlookups:firstitlooksforthecommandinthecurrentnamespace,
andthenintheglobalnamespace.Accordingly,ifcommandisrelativeandnamespaceisnot::,thelistreturnedhastwoelements:commandscopedbynamespace,asifitwereacommandinthenamespacenamespace;andcommandasifitwereacommandintheglobalnamespace.Otherwise,ifeithercommandisabsolute(itbeginswith::),ornamespaceis::,thelistcontainsonlycommandasifitwereacommandintheglobalnamespace.
Auto_qualifyisusedbytheauto-loadingfacilitiesinTcl,bothforproducingauto-loadingindexessuchaspkgIndex.tcl,andforperformingtheactualauto-loadingoffunctionsatruntime.
tcl_findLibrarybasenameversionpatchinitScriptenVarNamevarName
Thisisastandardsearchprocedureforusebyextensionsduringtheirinitialization.Theycallthisproceduretolookfortheirscriptlibraryinseveralstandarddirectories.Thelastcomponentofthenameofthelibrarydirectoryisnormallybasenameversion(e.g.,tk8.0),butitmightbe“library”wheninthebuildhierarchies.TheinitScriptfilewillbesourcedintotheinterpreteronceitisfound.ThedirectoryinwhichthisfileisfoundisstoredintotheglobalvariablevarName.Ifthisvariableisalreadydefined(e.g.,byCcodeduringapplicationinitialization)thennosearchingisdone.Otherwisethesearchlooksinthesedirectories:thedirectorynamedbytheenvironmentvariableenVarName;relativetotheTcllibrarydirectory;relativetotheexecutablefileinthestandardinstallationbinorbin/archdirectory;relativetotheexecutablefileinthecurrentbuildtree;relativetotheexecutablefileinaparallelbuildtree.
parrayarrayNamePrintsonstandardoutputthenamesandvaluesofalltheelementsinthearrayarrayName.ArrayNamemustbeanarrayaccessibletothecallerofparray.Itmaybeeitherlocalorglobal.
tcl_endOfWordstrstartReturnstheindexofthefirstend-of-wordlocationthatoccursafter
astartingindexstartinthestringstr.Anend-of-wordlocationisdefinedtobethefirstnon-wordcharacterfollowingthefirstwordcharacterafterthestartingpoint.Returns-1iftherearenomoreend-of-wordlocationsafterthestartingpoint.Seethedescriptionoftcl_wordcharsandtcl_nonwordcharsbelowformoredetailsonhowTcldetermineswhichcharactersarewordcharacters.
tcl_startOfNextWordstrstartReturnstheindexofthefirststart-of-wordlocationthatoccursafterastartingindexstartinthestringstr.Astart-of-wordlocationisdefinedtobethefirstwordcharacterfollowinganon-wordcharacter.Returns-1iftherearenomorestart-of-wordlocationsafterthestartingpoint.
tcl_startOfPreviousWordstrstartReturnstheindexofthefirststart-of-wordlocationthatoccursbeforeastartingindexstartinthestringstr.Returns-1iftherearenomorestart-of-wordlocationsbeforethestartingpoint.
tcl_wordBreakAfterstrstartReturnstheindexofthefirstwordboundaryafterthestartingindexstartinthestringstr.Returns-1iftherearenomoreboundariesafterthestartingpointinthegivenstring.Theindexreturnedreferstothesecondcharacterofthepairthatcomprisesaboundary.
tcl_wordBreakBeforestrstartReturnstheindexofthefirstwordboundarybeforethestartingindexstartinthestringstr.Returns-1iftherearenomoreboundariesbeforethestartingpointinthegivenstring.Theindexreturnedreferstothesecondcharacterofthepairthatcomprisesaboundary.
VARIABLES
ThefollowingglobalvariablesaredefinedorusedbytheproceduresintheTcllibrary:
auto_execs
Usedbyauto_execoktorecordinformationaboutwhetherparticularcommandsexistasexecutablefiles.
auto_indexUsedbyauto_loadtosavetheindexinformationreadfromdisk.
auto_noexecIfsettoanyvalue,thenunknownwillnotattempttoauto-execanycommands.
auto_noloadIfsettoanyvalue,thenunknownwillnotattempttoauto-loadanycommands.
auto_pathIfset,thenitmustcontainavalidTcllistgivingdirectoriestosearchduringauto-loadoperations.Thisvariableisinitializedduringstartuptocontain,inorder:thedirectorieslistedintheTCLLIBPATHenvironmentvariable,thedirectorynamedbythe$tcl_libraryvariable,theparentdirectoryof$tcl_library,thedirectorieslistedinthe$tcl_pkgPathvariable.
env(TCL_LIBRARY)Ifset,thenitspecifiesthelocationofthedirectorycontaininglibraryscripts(thevalueofthisvariablewillbeassignedtothetcl_libraryvariableandthereforereturnedbythecommandinfolibrary).Ifthisvariableisnotsetthenadefaultvalueisused.
env(TCLLIBPATH)Ifset,thenitmustcontainavalidTcllistgivingdirectoriestosearchduringauto-loadoperations.DirectoriesmustbespecifiedinTclformat,using“/”asthepathseparator,regardlessofplatform.Thisvariableisonlyusedwheninitializingtheauto_pathvariable.
tcl_nonwordcharsThisvariablecontainsaregularexpressionthatisusedbyroutinesliketcl_endOfWordtoidentifywhetheracharacterispartofawordornot.Ifthepatternmatchesacharacter,thecharacteris
consideredtobeanon-wordcharacter.OnWindowsplatforms,spaces,tabs,andnewlinesareconsiderednon-wordcharacters.UnderUnix,everythingbutnumbers,lettersandunderscoresareconsiderednon-wordcharacters.
tcl_wordcharsThisvariablecontainsaregularexpressionthatisusedbyroutinesliketcl_endOfWordtoidentifywhetheracharacterispartofawordornot.Ifthepatternmatchesacharacter,thecharacterisconsideredtobeawordcharacter.OnWindowsplatforms,wordsarecomprisedofanycharacterthatisnotaspace,tab,ornewline.UnderUnix,wordsarecomprisedofnumbers,lettersorunderscores.
SEEALSO
info,re_syntax
KEYWORDS
auto-exec,auto-load,library,unknown,word,whitespace
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1991-1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>append
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
append-Appendtovariable
SYNOPSIS
appendvarName?valuevaluevalue...?
DESCRIPTION
AppendallofthevalueargumentstothecurrentvalueofvariablevarName.IfvarNamedoesnotexist,itisgivenavalueequaltotheconcatenationofallthevaluearguments.TheresultofthiscommandisthenewvaluestoredinvariablevarName.Thiscommandprovidesanefficientwaytobuilduplongvariablesincrementally.Forexample,“appenda$b”ismuchmoreefficientthan“seta$a$b”if$aislong.
EXAMPLE
Buildingastringofcomma-separatednumberspiecemealusingaloop.
setvar0for{seti1}{$i
KEYWORDS
append,variable
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>eval
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
eval-EvaluateaTclscript
SYNOPSIS
evalarg?arg...?
DESCRIPTION
Evaltakesoneormorearguments,whichtogethercompriseaTclscriptcontainingoneormorecommands.Evalconcatenatesallitsargumentsinthesamefashionastheconcatcommand,passestheconcatenatedstringtotheTclinterpreterrecursively,andreturnstheresultofthatevaluation(oranyerrorgeneratedbyit).Notethatthelistcommandquotessequencesofwordsinsuchawaythattheyarenotfurtherexpandedbytheevalcommand.
EXAMPLES
Often,itisusefultostoreafragmentofascriptinavariableandexecuteitlateronwithextravaluesappended.ThistechniqueisusedinanumberofplacesthroughouttheTclcore(e.g.infcopy,lsortandtracecommandcallbacks).ThisexampleshowshowtodothisusingcoreTclcommands:
setscript{puts"loggingnow"lappend$myCurrentLogVar}setmyCurrentLogVarlog1
#Setupaswitchofloggingvariablepartwaythrough!after20000setmyCurrentLogVarlog2
for{seti0}{$i
catch,concat,error,interp,list,namespace,subst,tclvars,uplevel
KEYWORDS
concatenate,evaluate,script
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>lassign
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
lassign-Assignlistelementstovariables
SYNOPSIS
lassignlistvarName?varName...?
DESCRIPTION
ThiscommandtreatsthevaluelistasalistandassignssuccessiveelementsfromthatlisttothevariablesgivenbythevarNameargumentsinorder.Iftherearemorevariablenamesthanlistelements,theremainingvariablesaresettotheemptystring.Iftherearemorelistelementsthanvariables,alistofunassignedelementsisreturned.
EXAMPLES
Anillustrationofhowmultipleassignmentworks,andwhathappenswhenthereareeithertoofewortoomanyelements.
lassign{abc}xyz;#Emptyreturnputs$x;#Prints"a"puts$y;#Prints"b"puts$z;#Prints"c"
lassign{de}xyz;#Emptyreturnputs$x;#Prints"d"puts$y;#Prints"e"puts$z;#Prints""
lassign{fghi}xy;#Returns"hi"puts$x;#Prints"f"puts$y;#Prints"g"
Thelassigncommandhasotheruses.Itcanbeusedtocreatetheanalogueofthe“shift”commandinmanyshelllanguageslikethis:
set::argv[lassign$::argvargumentToReadOff]
SEEALSO
lindex,list,lset,set
KEYWORDS
assign,element,list,multiple,set,variable
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1992-1999KarlLehenbauer&MarkDiekhansCopyright©2004DonalK.Fellows
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>platform_shell
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
platform::shell-Systemidentificationsupportcodeandutilities
SYNOPSIS
packagerequireplatform::shell?1.1.4?platform::shell::genericshellplatform::shell::identifyshellplatform::shell::platformshell
DESCRIPTION
Theplatform::shellpackageprovidesseveralutilitycommandsusefulfortheidentificationofthearchitectureofaspecificTclshell.
ThispackageallowstheidentificationofthearchitectureofaspecificTclshelldifferentfromtheshellrunningthepackage.Theonlyrequirementisthattheothershell(identifiedbyitspath),isactuallyexecutableonthecurrentmachine.
Whileformostplatformthismeansthatthearchitectureoftheinterrogatedshellisidenticaltothearchitectureoftherunningshellthisisnotgenerallytrue.Acounterexampleareallplatformswhichhave32and64bitvariantsandwherea64bitsystemisabletorun32bitcode.Fortheserunningandinterrogatedshellmayhavedifferent32/64bitsettingsandthusdifferentidentifiers.
Forapplicationslikeacoderepositoryitisimportanttoidentifythearchitectureoftheshellwhichwillactuallyruntheinstalledpackages,versusthearchitectureoftheshellrunningtherepositorysoftware.
COMMANDS
platform::shell::identifyshellThiscommanddoesthesameidentificationasplatform::identify,forthespecifiedTclshell,incontrasttotherunningshell.
platform::shell::genericshellThiscommanddoesthesameidentificationasplatform::generic,forthespecifiedTclshell,incontrasttotherunningshell.
platform::shell::platformshellThiscommandreturnsthecontentsoftcl_platform(platform)forthespecifiedTclshell.
KEYWORDS
operatingsystem,cpuarchitecture,platform,architecture
Copyright©1995-1997RogerE.CritchlowJr.Copyright©2006-2008ActiveStateSoftwareInc
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>apply
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
apply-Applyananonymousfunction
SYNOPSIS
applyfunc?arg1arg2...?
DESCRIPTION
Thecommandapplyappliesthefunctionfunctotheargumentsarg1arg2...andreturnstheresult.
Thefunctionfuncisatwoelementlist{argsbody}orathreeelementlist{argsbodynamespace}(asifthelistcommandhadbeenused).Thefirstelementargsspecifiestheformalargumentstofunc.Thespecificationoftheformalargumentsargsissharedwiththeproccommand,andisdescribedindetailinthecorrespondingmanualpage.
ThecontentsofbodyareexecutedbytheTclinterpreterafterthelocalvariablescorrespondingtotheformalargumentsaregiventhevaluesoftheactualparametersarg1arg2....Whenbodyisbeingexecuted,variablenamesnormallyrefertolocalvariables,whicharecreatedautomaticallywhenreferencedanddeletedwhenapplyreturns.Onelocalvariableisautomaticallycreatedforeachofthefunction'sarguments.Globalvariablescanonlybeaccessedbyinvokingtheglobalcommandortheupvarcommand.Namespacevariablescanonlybeaccessedbyinvokingthevariablecommandortheupvarcommand.
TheinvocationofapplyaddsacallframetoTcl'sevaluationstack(thestackofframesaccessedviauplevel).Theexecutionofbodyproceeds
inthiscallframe,inthenamespacegivenbynamespaceorintheglobalnamespaceifnonewasspecified.Ifgiven,namespaceisinterpretedrelativetotheglobalnamespaceevenifitsnamedoesnotstartwith“::”.
Thesemanticsofapplycanalsobedescribedby:
procapply{funargs}{setlen[llength$fun]if{($len<2)||($len>3)}{error"can'tinterpret\"$fun\"asanonymousfunction"}lassign$funargListbodynssetname::$ns::[getGloballyUniqueName]setbody0{rename[lindex[infolevel0]0]{}}proc$name$argList${body0}$bodysetcode[catch{uplevel1$name$args}resopt]return-options$opt$res}
EXAMPLES
Thisshowshowtomakeasimplegeneralcommandthatappliesatransformationtoeachelementofalist.
procmap{lambdalist}{setresult{}foreachitem$list{lappendresult[apply$lambda$item]}return$result}
map{x{return[stringlength$x]:$x}}{abbcccdddd}→1:a2:bb3:ccc4:ddddmap{x{expr{$x**2+3*$x-2}}}{-4-3-2-101234}→2-2-4-4-2281626
Theapplycommandisalsousefulfordefiningcallbacksforuseinthetracecommand:
setvbl"123abc"traceaddvariablevblwrite{apply{{v1v2op}{upvar1$v1vputs"updatedvariableto\"$v\""}}}setvbl123setvblabc
SEEALSO
proc,uplevel
KEYWORDS
argument,procedure,anonymousfunction
Copyright©1995-1997RogerE.CritchlowJr.Copyright©2006MiguelSoferCopyright©2006DonalK.Fellows
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>exec
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEexec-Invokesubprocesses
SYNOPSISDESCRIPTION
-ignorestderr-keepnewline--||&<fileNamefileName>&fileName>>fileName2>>fileName>>&fileName>@fileId2>@fileId2>@1>&@fileId
PORTABILITYISSUESWindows(allversions)WindowsNTWindows9xUnix
UNIXEXAMPLESWINDOWSEXAMPLESSEEALSOKEYWORDS
NAME
exec-Invokesubprocesses
SYNOPSIS
exec?switches?arg?arg...?
DESCRIPTION
Thiscommandtreatsitsargumentsasthespecificationofoneormoresubprocessestoexecute.Theargumentstaketheformofastandardshellpipelinewhereeachargbecomesonewordofacommand,andeachdistinctcommandbecomesasubprocess.
Iftheinitialargumentstoexecstartwith-thentheyaretreatedascommand-lineswitchesandarenotpartofthepipelinespecification.Thefollowingswitchesarecurrentlysupported:
-ignorestderrStopstheexeccommandfromtreatingtheoutputofmessagestothepipeline'sstandarderrorchannelasanerrorcase.
-keepnewlineRetainsatrailingnewlineinthepipeline'soutput.Normallyatrailingnewlinewillbedeleted.
--Markstheendofswitches.Theargumentfollowingthisonewillbetreatedasthefirstargevenifitstartswitha-.
Ifanarg(orpairofargs)hasoneoftheformsdescribedbelowthenitisusedbyexectocontroltheflowofinputandoutputamongthesubprocess(es).Suchargumentswillnotbepassedtothesubprocess(es).Informssuchas“<fileName”,fileNamemayeitherbeinaseparateargumentfrom“
Separatesdistinctcommandsinthepipeline.Thestandardoutputoftheprecedingcommandwillbepipedintothestandardinputofthenextcommand.
|&Separatesdistinctcommandsinthepipeline.Bothstandardoutputandstandarderroroftheprecedingcommandwillbepipedintothestandardinputofthenextcommand.Thisformofredirectionoverridesformssuchas2>and>&.
<fileNameThefilenamedbyfileNameisopenedandusedasthestandardinputforthefirstcommandinthepipeline.
fileNameStandarderrorfromallcommandsinthepipelineisredirectedtothefilenamedfileName,overwritingitspreviouscontents.
>&fileNameBothstandardoutputfromthelastcommandandstandarderrorfromallcommandsareredirectedtothefilenamedfileName,overwritingitspreviouscontents.
>>fileNameStandardoutputfromthelastcommandisredirectedtothefile
namedfileName,appendingtoitratherthanoverwritingit.
2>>fileNameStandarderrorfromallcommandsinthepipelineisredirectedtothefilenamedfileName,appendingtoitratherthanoverwritingit.
>>&fileNameBothstandardoutputfromthelastcommandandstandarderrorfromallcommandsareredirectedtothefilenamedfileName,appendingtoitratherthanoverwritingit.
>@fileIdFileIdmustbetheidentifierforanopenfile,suchasthereturnvaluefromapreviouscalltoopen.StandardoutputfromthelastcommandisredirectedtofileId'sfile,whichmusthavebeenopenedforwriting.
2>@fileIdFileIdmustbetheidentifierforanopenfile,suchasthereturnvaluefromapreviouscalltoopen.StandarderrorfromallcommandsinthepipelineisredirectedtofileId'sfile.Thefilemusthavebeenopenedforwriting.
2>@1Standarderrorfromallcommandsinthepipelineisredirectedtothecommandresult.Thisoperatorisonlyvalidattheendofthecommandpipeline.
>&@fileIdFileIdmustbetheidentifierforanopenfile,suchasthereturnvaluefromapreviouscalltoopen.BothstandardoutputfromthelastcommandandstandarderrorfromallcommandsareredirectedtofileId'sfile.Thefilemusthavebeenopenedforwriting.
Ifstandardoutputhasnotbeenredirectedthentheexeccommandreturnsthestandardoutputfromthelastcommandinthepipeline,unless“2>@1”wasspecified,inwhichcasestandarderrorisincludedaswell.Ifanyofthecommandsinthepipelineexitabnormallyorare
killedorsuspended,thenexecwillreturnanerrorandtheerrormessagewillincludethepipeline'soutputfollowedbyerrormessagesdescribingtheabnormalterminations;the-errorcodereturnoptionwillcontainadditionalinformationaboutthelastabnormalterminationencountered.Ifanyofthecommandswritestoitsstandarderrorfileandthatstandarderrorisnotredirectedand-ignorestderrisnotspecified,thenexecwillreturnanerror;theerrormessagewillincludethepipeline'sstandardoutput,followedbymessagesaboutabnormalterminations(ifany),followedbythestandarderroroutput.
Ifthelastcharacteroftheresultorerrormessageisanewlinethenthatcharacterisnormallydeletedfromtheresultorerrormessage.ThisisconsistentwithotherTclreturnvalues,whichdonotnormallyendwithnewlines.However,if-keepnewlineisspecifiedthenthetrailingnewlineisretained.
Ifstandardinputisnotredirectedwith“
Windows(allversions)Readingfromorwritingtoasocket,usingthe“@fileId”notation,doesnotwork.Whenreadingfromasocket,a16-bitDOSapplicationwillhanganda32-bitapplicationwillreturnimmediatelywithend-of-file.Wheneithertypeofapplicationwritestoasocket,theinformationisinsteadsenttotheconsole,ifoneispresent,orisdiscarded.
TheTkconsoletextwidgetdoesnotproviderealstandardIOcapabilities.UnderTk,whenredirectingfromstandardinput,allapplicationswillseeanimmediateend-of-file;informationredirectedtostandardoutputorstandarderrorwillbediscarded.
EitherforwardorbackwardslashesareacceptedaspathseparatorsforargumentstoTclcommands.Whenexecutinganapplication,thepathnamespecifiedfortheapplicationmayalsocontainforwardorbackwardslashesaspathseparators.Bearinmind,however,thatmostWindowsapplicationsacceptargumentswithforwardslashesonlyasoptiondelimitersandbackslashesonlyinpaths.Anyargumentstoanapplicationthatspecifyapathnamewithforwardslasheswillnotautomaticallybeconvertedtousethebackslashcharacter.Ifanargumentcontainsforwardslashesasthepathseparator,itmayormaynotberecognizedasapathname,dependingontheprogram.
Additionally,whencallinga16-bitDOSorWindows3.Xapplication,allpathnamesmustusetheshort,cryptic,pathformat(e.g.,using“applba~1.def”insteadof“applbakery.default”),whichcanbeobtainedwiththe“fileattributesfileName-shortname”command.
Twoormoreforwardorbackwardslashesinarowinapathrefertoanetworkpath.Forexample,asimpleconcatenationoftherootdirectoryc:/withasubdirectory/windows/systemwillyieldc://windows/system(twoslashestogether),whichreferstothemountpointcalledsystemonthemachinecalledwindows(andthec:/isignored),andisnotequivalenttoc:/windows/system,whichdescribesadirectoryonthecurrentcomputer.Thefilejoincommandshouldbeusedtoconcatenatepathcomponents.
NotethattherearetwogeneraltypesofWin32consoleapplications:
[1]CLI—CommandLineInterface,simplestdioexchange.netstat.exeforexample.
[2]TUI—TextmodeUserInterface,anyapplicationthataccessestheconsoleAPIfordoingsuchthingsascursormovement,settingtextcolor,detectingkeypressesandmousemovement,etc.Anexamplewouldbetelnet.exefromWindows2000.Thesetypesofapplicationsarenotcommoninawindowsenvironment,butdoexist.
execwillnotworkwellwithTUIapplicationswhenaconsoleisnotpresent,asisdonewhenlaunchingapplicationsunderwish.Itisdesirabletohaveconsoleapplicationshiddenanddetached.Thisisadesigned-inlimitationasexecwantstocommunicateoverpipes.TheExpectextensionaddressesthisissuewhencommunicatingwithaTUIapplication.
WindowsNTWhenattemptingtoexecuteanapplication,execfirstsearchesforthenameasitwasspecified.Then,inorder,.com,.exe,and.batareappendedtotheendofthespecifiednameanditsearchesforthelongername.Ifadirectorynamewasnotspecifiedaspartoftheapplicationname,thefollowingdirectoriesareautomaticallysearchedinorderwhenattemptingtolocatetheapplication:
•ThedirectoryfromwhichtheTclexecutablewasloaded.
•Thecurrentdirectory.
•TheWindowsNT32-bitsystemdirectory.
•TheWindowsNT16-bitsystemdirectory.
•TheWindowsNThomedirectory.
•Thedirectorieslistedinthepath.
Inordertoexecuteshellbuilt-incommandslikedirandcopy,thecallermustprependthedesiredcommandwith“cmd.exe/c”becausebuilt-incommandsarenotimplementedusingexecutables.
Windows9xWhenattemptingtoexecuteanapplication,execfirstsearchesforthenameasitwasspecified.Then,inorder,.com,.exe,and.batareappendedtotheendofthespecifiednameanditsearchesforthelongername.Ifadirectorynamewasnotspecifiedaspartoftheapplicationname,thefollowingdirectoriesareautomaticallysearchedinorderwhenattemptingtolocatetheapplication:
•ThedirectoryfromwhichtheTclexecutablewasloaded.
•Thecurrentdirectory.
•TheWindows9xsystemdirectory.
•TheWindows9xhomedirectory.
•Thedirectorieslistedinthepath.
Inordertoexecuteshellbuilt-incommandslikedirandcopy,thecallermustprependthedesiredcommandwith“command.com/c”becausebuilt-incommandsarenotimplementedusingexecutables.
Oncea16-bitDOSapplicationhasreadstandardinputfromaconsoleandthenquit,allsubsequentlyrun16-bitDOSapplicationswillseethestandardinputasalreadyclosed.32-bitapplicationsdonothavethisproblemandwillruncorrectly,evenaftera16-bitDOSapplicationthinksthatstandardinputisclosed.Thereisnoknownworkaroundforthisbugatthistime.
RedirectionbetweentheNUL:deviceanda16-bitapplicationdoes
notalwayswork.WhenredirectingfromNUL:,someapplicationsmayhang,otherswillgetaninfinitestreamof“0x01”bytes,andsomewillactuallycorrectlygetanimmediateend-of-file;thebehaviorseemstodependuponsomethingcompiledintotheapplicationitself.Whenredirectinggreaterthan4KorsotoNUL:,someapplicationswillhang.Theaboveproblemsdonothappenwith32-bitapplications.
AllDOS16-bitapplicationsarerunsynchronously.Allstandardinputfromapipetoa16-bitDOSapplicationiscollectedintoatemporaryfile;theotherendofthepipemustbeclosedbeforethe16-bitDOSapplicationbeginsexecuting.Allstandardoutputorerrorfroma16-bitDOSapplicationtoapipeiscollectedintotemporaryfiles;theapplicationmustterminatebeforethetemporaryfilesareredirectedtothenextstageofthepipeline.ThisisduetoaworkaroundforaWindows95bugintheimplementationofpipes,andishowthestandardWindows95DOSshellhandlespipesitself.
Certainapplications,suchascommand.com,shouldnotbeexecutedinteractively.Applicationswhichdirectlyaccesstheconsolewindow,ratherthanreadingfromtheirstandardinputandwritingtotheirstandardoutputmayfail,hangTcl,orevenhangthesystemiftheirownprivateconsolewindowisnotavailabletothem.
UnixTheexeccommandisfullyfunctionalandworksasdescribed.
UNIXEXAMPLES
HerearesomeexamplesoftheuseoftheexeccommandonUnix.
Toexecuteasimpleprogramandgetitsresult:
execuname-a
Toexecuteaprogramthatcanreturnanon-zeroresult,youshould
wrapthecalltoexecincatchandcheckthecontentsofthe-errorcodereturnoptionifyouhaveanerror:
setstatus0if{[catch{execgrepfoobar.txt}resultsoptions]}{setdetails[dictget$options-errorcode]if{[lindex$details0]eq"CHILDSTATUS"}{setstatus[lindex$details2]}else{#Somekindofunexpectedfailure}}
WhentranslatingacommandfromaUnixshellinvocation,careshouldbetakenoverthefactthatsinglequotecharactershavenospecialsignificancetoTcl.Thus:
awk'{sum+=$1}END{printsum}'numbers.list
wouldbetranslatedintosomethinglike:
execawk{{sum+=$1}END{printsum}}numbers.list
Ifyouareconvertinginvocationsinvolvingshellglobbing,youshouldrememberthatTcldoesnothandleglobbingorexpandthingsintomultipleargumentsbydefault.Insteadyoushouldwritethingslikethis:
execls-l{*}[glob*.tcl]
WINDOWSEXAMPLES
HerearesomeexamplesoftheuseoftheexeccommandonWindows.
Tostartaninstanceofnotepadeditingafilewithoutwaitingfortheusertofinisheditingthefile:
execnotepadmyfile.txt&
Toprintatextfileusingnotepad:
execnotepad/pmyfile.txt
Ifaprogramcallsotherprograms,suchasiscommonwithcompilers,thenyoumayneedtoresorttobatchfilestohidetheconsolewindowsthatsometimespopup:
execcmp.batsomefile.c-osomefile
Withthefilecmp.batlookingsomethinglike:
@gcc%1%2%3%4%5%6%7%8%9
Sometimesyouneedtobecareful,asdifferentprogramsmayhavethesamenameandbeinthepath.ItcanthenhappenthattypingacommandattheDOSpromptfindsadifferentprogramthanthesamecommandrunviaexec.Thisisbecauseofthe(documented)differencesinbehaviourbetweenexecandDOSbatchfiles.
Whenindoubt,usethecommandauto_execok:itwillreturnthecompletepathtotheprogramasseenbytheexeccommand.Thisappliesespeciallywhenyouwanttorun“internal”commandslikedirfromaTclscript(ifyoujustwanttolistfilenames,usetheglobcommand.)Todothat,usethis:
exec{*}[auto_execokdir]*.tcl
SEEALSO
error,open
KEYWORDS
execute,pipeline,redirection,subprocess
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.Copyright©2006DonalK.Fellows.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>lindex
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
lindex-Retrieveanelementfromalist
SYNOPSIS
lindexlist?index...?
DESCRIPTION
Thelindexcommandacceptsaparameter,list,whichittreatsasaTcllist.Italsoacceptszeroormoreindicesintothelist.Theindicesmaybepresentedeitherconsecutivelyonthecommandline,orgroupedinaTcllistandpresentedasasingleargument.
Ifnoindicesarepresented,thecommandtakestheform:
lindexlist
or
lindexlist{}
Inthiscase,thereturnvalueoflindexissimplythevalueofthelistparameter.
Whenpresentedwithasingleindex,thelindexcommandtreatslistasaTcllistandreturnstheindex'thelementfromit(0referstothefirstelementofthelist).Inextractingtheelement,lindexobservesthesame
rulesconcerningbracesandquotesandbackslashesastheTclcommandinterpreter;however,variablesubstitutionandcommandsubstitutiondonotoccur.Ifindexisnegativeorgreaterthanorequaltothenumberofelementsinvalue,thenanemptystringisreturned.Theinterpretationofeachsimpleindexvalueisthesameasforthecommandstringindex,supportingsimpleindexarithmeticandindicesrelativetotheendofthelist.
Ifadditionalindexargumentsaresupplied,theneachargumentisusedinturntoselectanelementfromthepreviousindexingoperation,allowingthescripttoselectelementsfromsublists.Thecommand,
lindex$a123
or
lindex$a{123}
issynonymouswith
lindex[lindex[lindex$a1]2]3
EXAMPLES
lindex{abc}→abclindex{abc}{}→abclindex{abc}0→alindex{abc}2
→clindex{abc}end→clindex{abc}end-1→blindex{{abc}{def}{ghi}}21→hlindex{{abc}{def}{ghi}}{21}→hlindex{{{ab}{cd}}{{ef}{gh}}}110→glindex{{{ab}{cd}}{{ef}{gh}}}{110}→g
SEEALSO
list,lappend,linsert,llength,lsearch,lset,lsort,lrange,lreplace,string
KEYWORDS
element,index,list
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.Copyright©2001byKevinB.Kenny.Allrightsreserved.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>proc
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
proc-CreateaTclprocedure
SYNOPSIS
procnameargsbody
DESCRIPTION
TheproccommandcreatesanewTclprocedurenamedname,replacinganyexistingcommandorproceduretheremayhavebeenbythatname.Wheneverthenewcommandisinvoked,thecontentsofbodywillbeexecutedbytheTclinterpreter.Normally,nameisunqualified(doesnotincludethenamesofanycontainingnamespaces),andthenewprocedureiscreatedinthecurrentnamespace.Ifnameincludesanynamespacequalifiers,theprocedureiscreatedinthespecifiednamespace.Argsspecifiestheformalargumentstotheprocedure.Itconsistsofalist,possiblyempty,eachofwhoseelementsspecifiesoneargument.Eachargumentspecifierisalsoalistwitheitheroneortwofields.Ifthereisonlyasinglefieldinthespecifierthenitisthenameoftheargument;iftherearetwofields,thenthefirstistheargumentnameandthesecondisitsdefaultvalue.Argumentswithdefaultvaluesthatarefollowedbynon-defaultedargumentsbecomerequiredarguments.In8.6thiswillbeconsideredanerror.
Whennameisinvokedalocalvariablewillbecreatedforeachoftheformalargumentstotheprocedure;itsvaluewillbethevalueofcorrespondingargumentintheinvokingcommandortheargument'sdefaultvalue.Actualargumentsareassignedtoformalargumentsstrictlyinorder.Argumentswithdefaultvaluesneednotbespecifiedin
aprocedureinvocation.However,theremustbeenoughactualargumentsforalltheformalargumentsthatdonothavedefaults,andtheremustnotbeanyextraactualarguments.Argumentswithdefaultvaluesthatarefollowedbynon-defaultedargumentsbecomerequiredarguments(in8.6itwillbeconsideredanerror).Thereisonespecialcasetopermitprocedureswithvariablenumbersofarguments.Ifthelastformalargumenthasthenameargs,thenacalltotheproceduremaycontainmoreactualargumentsthantheprocedurehasformals.Inthiscase,alloftheactualargumentsstartingattheonethatwouldbeassignedtoargsarecombinedintoalist(asifthelistcommandhadbeenused);thiscombinedvalueisassignedtothelocalvariableargs.
Whenbodyisbeingexecuted,variablenamesnormallyrefertolocalvariables,whicharecreatedautomaticallywhenreferencedanddeletedwhentheprocedurereturns.Onelocalvariableisautomaticallycreatedforeachoftheprocedure'sarguments.Othervariablescanonlybeaccessedbyinvokingoneoftheglobal,variable,upvarornamespaceupvarcommands.
Theproccommandreturnsanemptystring.Whenaprocedureisinvoked,theprocedure'sreturnvalueisthevaluespecifiedinareturncommand.Iftheproceduredoesnotexecuteanexplicitreturn,thenitsreturnvalueisthevalueofthelastcommandexecutedintheprocedure'sbody.Ifanerroroccurswhileexecutingtheprocedurebody,thentheprocedure-as-a-wholewillreturnthatsameerror.
EXAMPLES
Thisisaprocedurethatacceptsarbitrarilymanyargumentsandprintsthemout,onebyone.
procprintArgumentsargs{foreacharg$args{puts$arg}}
Thisprocedureisabitliketheincrcommand,exceptitmultipliesthecontentsofthenamedvariablebythevalue,whichdefaultsto2:
procmult{varName{multiplier2}}{upvar1$varNamevarsetvar[expr{$var*$multiplier}]}
SEEALSO
info,unknown
KEYWORDS
argument,procedure
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>array
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAMEarray-Manipulatearrayvariables
SYNOPSISDESCRIPTION
arrayanymorearrayNamesearchIdarraydonesearcharrayNamesearchIdarrayexistsarrayNamearraygetarrayName?pattern?arraynamesarrayName?mode??pattern?arraynextelementarrayNamesearchIdarraysetarrayNamelistarraysizearrayNamearraystartsearcharrayNamearraystatisticsarrayNamearrayunsetarrayName?pattern?
EXAMPLESSEEALSOKEYWORDS
NAME
array-Manipulatearrayvariables
SYNOPSIS
arrayoptionarrayName?argarg...?
DESCRIPTION
ThiscommandperformsoneofseveraloperationsonthevariablegivenbyarrayName.Unlessotherwisespecifiedforindividualcommandsbelow,arrayNamemustbethenameofanexistingarrayvariable.The
optionargumentdetermineswhatactioniscarriedoutbythecommand.Thelegaloptions(whichmaybeabbreviated)are:
arrayanymorearrayNamesearchIdReturns1ifthereareanymoreelementslefttobeprocessedinanarraysearch,0ifallelementshavealreadybeenreturned.SearchIdindicateswhichsearchonarrayNametocheck,andmusthavebeenthereturnvaluefromapreviousinvocationofarraystartsearch.Thisoptionisparticularlyusefulifanarrayhasanelementwithanemptyname,sincethereturnvaluefromarraynextelementwillnotindicatewhetherthesearchhasbeencompleted.
arraydonesearcharrayNamesearchIdThiscommandterminatesanarraysearchanddestroysallthestateassociatedwiththatsearch.SearchIdindicateswhichsearchonarrayNametodestroy,andmusthavebeenthereturnvaluefromapreviousinvocationofarraystartsearch.Returnsanemptystring.
arrayexistsarrayNameReturns1ifarrayNameisanarrayvariable,0ifthereisnovariablebythatnameorifitisascalarvariable.
arraygetarrayName?pattern?Returnsalistcontainingpairsofelements.ThefirstelementineachpairisthenameofanelementinarrayNameandthesecondelementofeachpairisthevalueofthearrayelement.Theorderofthepairsisundefined.Ifpatternisnotspecified,thenalloftheelementsofthearrayareincludedintheresult.Ifpatternisspecified,thenonlythoseelementswhosenamesmatchpattern(usingthematchingrulesofstringmatch)areincluded.IfarrayNameisnotthenameofanarrayvariable,orifthearraycontainsnoelements,thenanemptylistisreturned.Iftracesonthearraymodifythelistofelements,theelementsreturnedarethosethatexistbothbeforeandafterthecalltoarrayget.
arraynamesarrayName?mode??pattern?
Returnsalistcontainingthenamesofalloftheelementsinthearraythatmatchpattern.Modemaybeoneof-exact,-glob,or-regexp.Ifspecified,modedesignateswhichmatchingrulestousetomatchpatternagainstthenamesoftheelementsinthearray.Ifnotspecified,modedefaultsto-glob.Seethedocumentationforstringmatchforinformationonglobstylematching,andthedocumentationforregexpforinformationonregexpmatching.Ifpatternisomittedthenthecommandreturnsalloftheelementnamesinthearray.Ifthereareno(matching)elementsinthearray,orifarrayNameisnotthenameofanarrayvariable,thenanemptystringisreturned.
arraynextelementarrayNamesearchIdReturnsthenameofthenextelementinarrayName,oranemptystringifallelementsofarrayNamehavealreadybeenreturnedinthissearch.ThesearchIdargumentidentifiesthesearch,andmusthavebeenthereturnvalueofanarraystartsearchcommand.Warning:ifelementsareaddedtoordeletedfromthearray,thenallsearchesareautomaticallyterminatedjustasifarraydonesearchhadbeeninvoked;thiswillcausearraynextelementoperationstofailforthosesearches.
arraysetarrayNamelistSetsthevaluesofoneormoreelementsinarrayName.listmusthaveaformlikethatreturnedbyarrayget,consistingofanevennumberofelements.Eachodd-numberedelementinlististreatedasanelementnamewithinarrayName,andthefollowingelementinlistisusedasanewvalueforthatarrayelement.IfthevariablearrayNamedoesnotalreadyexistandlistisempty,arrayNameiscreatedwithanemptyarrayvalue.
arraysizearrayNameReturnsadecimalstringgivingthenumberofelementsinthearray.IfarrayNameisnotthenameofanarraythen0isreturned.
arraystartsearcharrayNameThiscommandinitializesanelement-by-elementsearchthroughthearraygivenbyarrayName,suchthatinvocationsofthearray
nextelementcommandwillreturnthenamesoftheindividualelementsinthearray.Whenthesearchhasbeencompleted,thearraydonesearchcommandshouldbeinvoked.Thereturnvalueisasearchidentifierthatmustbeusedinarraynextelementandarraydonesearchcommands;itallowsmultiplesearchestobeunderwaysimultaneouslyforthesamearray.Itiscurrentlymoreefficientandeasiertouseeitherthearraygetorarraynames,togetherwithforeach,toiterateoverallbutverylargearrays.Seetheexamplesbelowforhowtodothis.
arraystatisticsarrayNameReturnsstatisticsaboutthedistributionofdatawithinthehashtablethatrepresentsthearray.Thisinformationincludesthenumberofentriesinthetable,thenumberofbuckets,andtheutilizationofthebuckets.
arrayunsetarrayName?pattern?Unsetsalloftheelementsinthearraythatmatchpattern(usingthematchingrulesofstringmatch).IfarrayNameisnotthenameofanarrayvariableortherearenomatchingelementsinthearray,noerrorwillberaised.IfpatternisomittedandarrayNameisanarrayvariable,thenthecommandunsetstheentirearray.Thecommandalwaysreturnsanemptystring.
EXAMPLES
arraysetcolorcount{red1green5blue4white9}
foreach{colorcount}[arraygetcolorcount]{puts"Color:$colorCount:$count"}
→Color:blueCount:4Color:whiteCount:9Color:greenCount:5Color:redCount:1
foreachcolor[arraynamescolorcount]{puts"Color:$colorCount:$colorcount($color)"}→Color:blueCount:4Color:whiteCount:9Color:greenCount:5Color:redCount:1
foreachcolor[lsort[arraynamescolorcount]]{puts"Color:$colorCount:$colorcount($color)"}→Color:blueCount:4Color:greenCount:5Color:redCount:1Color:whiteCount:9
arraystatisticscolorcount→4entriesintable,4bucketsnumberofbucketswith0entries:1numberofbucketswith1entries:2numberofbucketswith2entries:1numberofbucketswith3entries:0numberofbucketswith4entries:0numberofbucketswith5entries:0numberofbucketswith6entries:0numberofbucketswith7entries:0numberofbucketswith8entries:0numberofbucketswith9entries:0numberofbucketswith10ormoreentries:0averagesearchdistanceforentry:1.2
SEEALSO
list,string,variable,trace,foreach
KEYWORDS
array,elementnames,search
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993-1994TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>exit
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
exit-Endtheapplication
SYNOPSIS
exit?returnCode?
DESCRIPTION
Terminatetheprocess,returningreturnCodetothesystemastheexitstatus.IfreturnCodeisnotspecifiedthenitdefaultsto0.
EXAMPLE
Sincenon-zeroexitcodesareusuallyinterpretedaserrorcasesbythecallingprocess,theexitcommandisanimportantpartofsignalingthatsomethingfatalhasgonewrong.Thiscodefragmentisusefulinscriptstoactasageneralproblemtrap:
procmain{}{#...puttherealmaincodeinhere...}
if{[catch{main}msgoptions]}{putsstderr"unexpectedscripterror:$msg"if{[infoexistenv(DEBUG)]}{putsstderr"----BEGINTRACE----"putsstderr[dictget$options-errorinfo]putsstderr"----ENDTRACE----"}
#Reservecode1for"expected"errorexits...exit2}
SEEALSO
exec
KEYWORDS
exit,process
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>linsert
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
linsert-Insertelementsintoalist
SYNOPSIS
linsertlistindexelement?elementelement...?
DESCRIPTION
Thiscommandproducesanewlistfromlistbyinsertingalloftheelementargumentsjustbeforetheindex'thelementoflist.Eachelementargumentwillbecomeaseparateelementofthenewlist.Ifindexislessthanorequaltozero,thenthenewelementsareinsertedatthebeginningofthelist.Theinterpretationoftheindexvalueisthesameasforthecommandstringindex,supportingsimpleindexarithmeticandindicesrelativetotheendofthelist.
EXAMPLE
Puttingsomevaluesintoalist,firstindexingfromthestartandthenindexingfromtheend,andthenchainingthemtogether:
setoldList{thefoxjumpsoverthedog}setmidList[linsert$oldList1quick]setnewList[linsert$midListend-1lazy]#Theoldlistsstillexistthough...setnewerList[linsert[linsert$oldListend-1quick]1lazy]
SEEALSO
list,lappend,lindex,llength,lsearch,lset,lsort,lrange,lreplace,string
KEYWORDS
element,insert,list
Copyright©1995-1997RogerE.CritchlowJr.Copyright©1993TheRegentsoftheUniversityofCalifornia.Copyright©1994-1996SunMicrosystems,Inc.Copyright©2001KevinB.Kenny.Allrightsreserved.
Tcl8.5.8/Tk8.5.8Documentation>TclCmd>puts
Tcl/TkApplications|TclCommands|TkCommands|TclLibrary|TkLibrary
NAME
puts-Writetoachannel
SYNOPSIS
puts?-nonewline??channelId?string
DESCRIPTION
WritesthecharactersgivenbystringtothechannelgivenbychannelId.
ChannelIdmustbeanidentifierforanopenchannelsuchasaTclstandardchannel(stdoutorstderr),thereturnvaluefromaninvocationofopenorsocket,ortheresultofachannelcreationcommandprovidedbyaTclextension.Thechannelmusthavebeenopenedforoutput.
IfnochannelIdisspecifiedthenitdefaultstostdout.Putsnormallyoutputsanewlinecharacterafterstring,butthisfeaturemaybesuppressedbyspecifyingthe-nonewlineswitch.
Newlinecharactersintheoutputaretranslatedbyputstoplatform-specificend-of-linesequencesaccordingtothecurrentvalueofthe-translationoptionforthechannel(forexample,onPCsnewlinesarenormallyreplacedwithcarriage-return-linefeedsequences.Seethefconfiguremanualentryforadiscussiononwaysinwhichfconfigurewillalteroutput.
Tclbuffersoutputinternally,socharacterswrittenwithputsmaynotappearimmediatelyontheoutputfileordevice;Tclwillnormallydelayoutputuntilthebufferisfullorthechannelisclosed.Youcanforce
outputtoappearimmediatelywiththeflushcommand.
Whentheoutputbufferfillsup,theputscommandwillnormallyblockuntilallthebuffereddatahasbeenacceptedforoutputbytheoperatingsystem.IfchannelIdisinnonblockingmodethentheputscommandwillnotblockeveniftheoperatingsystemcannotacceptthedata.Instead,Tclcontinuestobufferthedataandwritesitinthebackgroundasfastastheunderlyingfileordevicecanacceptit.TheapplicationmustusetheTcleventloopfornonblockingoutputtowork;otherwiseTclneverfindsoutthatthefileordeviceisreadyformoreoutputdata.Itispossibleforanarbitrarilylargeamountofdatatobebufferedforachannelinnonblockingmode,whichcouldconsumealargeamountofmemory.Toavoidwastingmemory,nonblockingI/Oshouldnormallybeusedinanevent-drivenfashionwiththefileeventcommand(donotinvokeputsunlessyouhaverecentlybeennotifiedviaafileeventthatthechannelisreadyformoreoutputdata).
EXAMPLES
Writeashortmessagetotheconsole(orwhereverstdoutisdirected):
puts"Hello,World!"
Printamessageinseveralparts:
puts-nonewline"Hello,"puts"World!"
Printamessagetothestandarderrorchannel:
putsstderr"Hello,World!"
Appendalogmessaget