Timing Diagram Editing and Analysis

B.2 Perl Data Types

B.2 Perl Data Types

Previous topic Next topic  

B.2 Perl Data Types

Previous topic Next topic  

A Perl variable can be one of three data types: scalar (contains a single value), array (array of scalar values indexed using an integer), and associative arrays (array of scalar values indexed using a string). In Perl, the type of a variable dictates the first character of its name.

Scalars begin with a $ (e.g., $myValue)

Arrays begin with a @ (e.g., @myArray)

Associative arrays (sometimes referred to as hashes) begin with a % (e.g., %myHash).

Scalar values can store character strings, numbers, and references (Perl equivalent of pointers). Scalar values are automatically converted between strings and numbers depending on what the function they are passed to expects. Arrays contain an indexed list of scalar values. An associative array contains a set of key-value pairs. A value in an associative array is accessed by specifying the associated key.

Global Variables in Perl

Perl contains a number of pre-defined global variables. To distinguish these variables from user-created variables, the pre-defined variable names are all two characters where the first character sets the data type ($,@,or %) and the second character is a non-alphabetic character.

The most important pre-defined variable is $_. $_ is the default scalar upon which many functions automatically operate if the functions are called without parameters.

For example, the statement:

$l = <STDIN>;

reads a line of characters from standard input into the variable $l. If the result of <STDIN> wasn't assigned to $l:

<STDIN>;

then $_ would be assigned the line of characters.

The second most important pre-defined variable is @_. @_ is the array used to pass arguments to subroutines. At the beginning of most subroutines you will see a statement similar to the following:

my ($var1,$var2) = @_;

This copies the first argument from the subroutine call into $var1 and the second argument into $var2.

Using Variable Interpolation in Perl Text Strings

Text string literals in Perl can be surrounded by either single quotes or double quotes. Text strings surrounded by single quotes are taken literally without any translation (except for \' and \\ in order to allow single quotes and back slashes to be placed in a single quoted string). Text strings surround by double quotes, however, are subject to backslash and variable interpolation. Backslash interpolation means that character sequences such as \n (newline) and \t (tab) are translated by Perl to the appropriate ASCII code. Variable interpolation means that Perl variables embedded in the string are automatically replaced with their values. For example, if a variable named $state had a value of '0x1111', the string literal:

"ADDRESS <= $state after 10 ns"

would be translated by Perl to:

'ADDRESS <= 0x1111 after 10 ns'