---
title: Creating New Subroutines in TrafficScript
slug: ps/help/en_us/vtm/tsg/creating-new-subroutines-in-trafficscript
docTags: 
createdAt: 2026-08-02T09:41:21.264Z
---

You can create new TrafficScript subroutines to improve the efficiency of your software. Once created, these routines can be used in rules or procedures just like the predefined functions.

### Syntax

The syntax to create a new subroutine is:

```bash
sub function_name ($var1, $var2)
{
      <code>
      return "return value"
}
```

Subroutines can be called just as you would call any normal function:

```bash
$ret = function_name( $foo, $var );
```

This example would return the value given by the subroutine into the variable $ret.

### Subroutine Position and Name Restrictions

User subroutine names cannot be the same as built-in TrafficScript functions.

Subroutines can be declared above or below where they are used. For example, the following code is correct:

```bash
test();
sub test()
{
     log.info("Attention! Test running");
}
```

### Local Variables

Variables within subroutines are local to that section and do not affect the result when used outside of the subroutine.

For example, the following lines of code print out an empty string, as $var is not available (passed in as an argument) within the subroutine:

```bash
$var = "abc";
sub function()
{
      log.info($var);
}
function();

```

### $1 to $9 Variables

TrafficScript uses $1 to $9 as global variables, so they can be used to return extra data from subroutines in addition to the (optional) return statement that returns a single value.

For example, the following code prints "Hello World":

```bash
sub greetings()
{
     $1="Hello ";
return "World"
}
$ret = greetings();log.info($1 . $ret)
```
