Variables

Variables are objects that hold values. In TPT, a variable may hold a value of type integer, string, array of values, or hash of values.

A variable in TPT is identified in plain-text as ${id} and in an expression as just id, where id is the name of the variable. The value of a variable is set using the @set TPT command.

@set(id, 123)

@set(id, "The red fox runs.")

A variable may also be cleared using the @unset TPT command.

@unset(id)

See Example 2.2 for an example of how variables may be used in a template.

Example 2.2. Contents of a fruit basket

Listing of fruitbasket.tpt

@set(fruit, "Apple")
@set(basket, 12)
The basket holds ${basket} ${fruit}s.

Output of fruitbasket.tpt



The basket holds 12 Apples.

Variables can also hold more complex values, such as arrays or hashes. Array variables look like,

${array[index]}

and hashes look like,

${array.member}

In arrays, the index can be either a number or an expression that evaluates to a number. Example 2.3 demonstrates how to set a variable to an array, then read the variable.

Example 2.3. A fruit basket array

Listing of fruity.tpt

@set(basket, "apple", "orange", "lime", "banana", "pear")\
The fruit basket contains \
@foreach fruit (basket) { ${fruit} }.

Output of fruity.tpt

The fruit basket contains apple orange lime banana pear .

Note the use of spaces in this example. Backslashes are used to join lines. For more details about controlling whitespace and carriage returns, see the section called “Whitespace & Carriage Returns”.

Example 2.4 demonstrates how to use an array index in a creative fashion.

Example 2.4. Random array index

Listing of randfruit.tpt

@set(basket, "apple", "orange", "lime", "banana", "pear")\
The fruit of the day is ${basket[@rand(@size(basket))]}.

Possible output of randfruit.tpt

The fruit of the day is banana.

To determine the type of variable, use @isarray, @isscalar, and @ishash.