You are on page 1of 11

The syntax for a scalar variable is $variable_name.

A variable name is set up and addressed in


the same way as Bourne shell variables. To assign values to a scalar, you use statements like
these:
$name="Kamran";
$number=100;
$phone_Number='5551232';

A variable in Perl is evaluated at runtime to derive a value that is one of the following: a string, a
number, or a pointer to scalar. (To see the use of pointers and references, refer to Chapter 3,
"References.")
To print out the value of a variable, you use a print statement. Therefore, to print the value of
$name, you would make the following call:
print$name;

The value of $name is printed to the screen. Perl scripts "expect" input from a standard input (the
keyboard) and to write to the standard output. Of course, you can also use the print statement to
print the values of special variables that are built into Perl.

Special Variables
Table 2.1 lists the special variables in Perl. The first column contains the variable, and the second
contains a verbose name that you can use to make the code readable. The third column in the
table describes the contents of each variable.
You can use the verbose names (in column 2) by including the following line in the beginning of
your code:
useEnglish;

This statement will let you use the English.pm module in your code. (I cover the use of modules
in Chapter 4, "Introduction to Perl Modules.") Not all Perl variables have an equivalent name in
the English.pm module. The entry "n/a" in the second column indicates that there is not an
English name for the variable.
Table 2.1. Special variables in Perl.
Variable

English Name

Description

$_

$ARG

The default input and


output pattern searching
space

$1$9

n/a

The subpattern from the


last set of parentheses in a
pattern match

$&

$MATch

The last pattern matched


(RO)

$`

$PREMATch

The string preceding a


pattern match (RO)

$POSTMATch

The string following a


pattern match (RO)

$+

$LAST_PAREN_MATch

The last bracket matched


in a pattern (RO)

$*

$MULTILINE_MATchING

Set to 1 to enable multiline matching; set to 0 by


default

$.

$INPUT_LINE_NUMBER

The current input line


number; reset on close()
call only

$/

$INPUT_RECORD_SEPARATOR

The newline by default

$|

$AUTO_FLUSH

If set to 1, forces a flush


on every write or print;
0 by default

$,

$OUTPUT_FIELD_SEPARATOR

Specifies what is printed


between fields

$\

$INPUT_RECORD_SEPARATOR

The output record


separator for the print
operator

$"

$LIST_SEPARATOR

The separator for elements


within a list

$;

$SUBSCRIPT_SEPARATOR

The character for


multidimensional array

emulation
$#

$FORMAT

Output format for printed


numbers

$%

$FORMAT_PAGE_NUMBER

The current page number

$=

$FORMAT_LINES_PER_PAGE

The number of lines per


page

$FORMAT_LINES_LEFT

The number of lines still


left to draw on the page

$~

$FORMAT_NAME

The name of the current


format being used

$^

$FORMAT_TOP_NAME

The name of the current


top-of-page format

$:

$FORMAT_LINE_BREAK_chARACTERS

The set of characters after


which a string can be
broken up to fill with
continuation characters

}
unless(condition1){#oppositeof"if"statement.
...dothisifconditionisfalse;
}

The condition in these blocks of code is anything from a Perl variable to an expression that
returns either a true or false value. A true value is a non-zero value or a non-empty string.
Code blocks can be declared within code blocks to create levels of code blocks. Variables
declared in one code block are usually global to the rest of the program. To keep the scope of the
variable limited to the code block in which it is declared, use the my$variableName syntax. If
you declare with local$variableName syntax, the $variableName will be available to all
lower levels but not outside the code block.
Figure 2.1 illustrates how the scoping rules work in Perl. The main block declares two variables,
$x and $y. There are two blocks of code between curly braces, block A and block B. The variable
$x is not available to either of these blocks, but $y will be available.
Figure 2.1 : Scoping rules in Perl

Because block A is declared in the main block, the code in it will be able to access $y but not $x
because $x is declared as "my". The variable $f will not be available to other blocks of code even
if they are declared within block A. The variable $g is not declared as "local" or "my", so it's
not visible to the main module nor to block B.
The code in block B declares two variables, $k and $m. The variable $k can be assigned the value
of $g, provided that the code in block A is called before the code in block B. If the code in block
B is called before the code in block A, the variable $g will not be declared, and a value of
'undef' will be assigned to $k. Also, $m cannot use the value of $f because $f is declared in
block A as a "my" variable. The values of $y and $g are available to code in block B.
Finally, another code block (call it C) could be assigned in block B. Block C is not shown in the
figure. All variables in this new block C that are declared as neither "my" nor "local" would be
available to blocks A and B and the main program. Code in block C would not be able to access
variables $f, $k, and $m because they are declared as "my". The variable $g would not be
available to code in block B or C because it is local to block A.
Keep in mind that variables in code blocks are also declared at the first time they are assigned a
value. This creation includes arrays and strings. Variables are then evaluated by the parser when
they appear in code, and even in strings. There are times when you do not want the variable to be
evaluated. This is the time when you should be aware of quoting rules in Perl.

Quoting Rules
Three different types of quotes can be used in Perl. Double quotes (") are used to enclose strings.
Any scalars in double-quoted strings are evaluated by Perl. To force Perl not to evaluate anything
in a quote, you'll have to use single quotes ('). Anything that looks like code and is not quoted is
interpreted as code by the Perl interpreter, which attempts to evaluate the code as an expression
or a set of executable code statements. Finally, to run some values in a shell program and get its
return value back, use the back quote (`) symbol. See the Perl script in Listing 2.1 for an
example.

Listing 2.1. Quoting in a Perl script.


1#!/usr/bin/perl
2$folks="100";
3print"\$folks=$folks\n";
4print'\$folks=$folks\n';
5print"\n\nBEEP!\a\LSOMEBLANK\ELINESHERE\n\n";
6$date=`date+%D`;
7print"Todayis[$date]\n";
8chop$date;
9print"Dateafterchoppingoffcarriagereturn:[".$date."]\n";

The output from the code in Listing 2.1 is as follows:


$folks=100
\$folks=$folks\n
BEEP!someblankLINESHERE
Todayis[03/29/96
]
Dateafterchoppingoffcarriagereturn:[03/29/96]

Let's go over the code shown in Listing 2.1. First of all, note that the actual listing did not have
line numbers. The line numbers in this and subsequent scripts are used to identify specific lines
of code.
Line 1 is the mandatory first line of the Perl script. Change the path shown in Listing 2.1 to
where your Perl interpreter is located if the script does not run. Be sure to make a similar change
to the rest of the source listings in this book.
Line 2 assigns a string value to the $folks variable. Note that you did not have to declare the
variable $folks because it was created when used for the first time.
Line 3 prints the value of $folks in between double quotes. The $ sign in $folks has to be
escaped with a backslash to prevent Perl from evaluating the value of $folks instead of printing
the following line:
$folks=100

In line 4, Perl does not evaluate anything between the single quotes. Therefore, the entire
contents of the line are left untouched and printed here:
\$folks=$folks\n

Perl has several special characters to format text data for you. Line 5 prints multiple blank lines
with the \n character and beeps at the terminal. Notice how the words SOMEBLANK are printed in
lowercase letters. This is because they are encased between the \L and \E special characters,
which force all characters to be lowercase. Some of these special characters are listed in Table
2.2.
Table 2.2. Special characters in Perl.
Character

Meaning

\\

Backslash.

\0ooo

Octal number in ooo (for example, \0213).

\a

Beep.

\b

Backspace.

\c

Inserts the next character literally (for example, \$ puts $).

\cC

Inserts control character C.

\l

Next character is lowercase.

\L \E

All characters between \L and \E are lowercase.

\n

New line (line feed).

\r

Carriage return (MS-DOS).

\t

Tab.

\u

Next character is uppercase.

\U \E

All characters between \U and \E are uppercase.

\x##

Hex number in ## (for example, \x1d).

In line 6, the script uses the back quotes (`) to execute a command and return the results in the
$date variable. The string in between the two back quotes is what you would type at the
command line, with one exception: if you use Perl variables in the command line for the back
quotes, Perl evaluates these variables before passing them off to the shell for execution. For
example, line 6 could be rewritten as this:
$parm="+%D";
$date=`$date$parm`;

The returned value in $date is printed out in line 7. Note that there is an extra carriage return in
the text for data. To remove it, use the chop command as shown in line 8.
Then in line 9 the $date output is shown to print correctly. Note how the period (.) is used to
concatenate three strings together for the output.

It's easy to construct strings in Perl with the period (.) operator. Given two strings, $first and
$last, you can construct the string $fullname like this to get "JimSmith":
$first="Jim";
$last="Smith";
$fullname=$first."".$last;

Numbers in Perl are stored as floating-point numbers; even variables used as integers are really
stored as floating point numbers. There are a set of operations you can do with numbers. These
operations are listed in Table 2.3. The table also lists Boolean operators.
Table 2.3. Numeric operations with Perl.
Operation

Description

$r=$x+$y

Adds $x to $y and assigns the result to $r

$r=$x$y

Subtracts $y from $x and assigns the result to $r

$r=$x*$y

Multiplies $y and $x and assigns the result to $r

$r=$x/$y

Divides $x by $y and assigns the result to $r

$r=$x%$y

Modulo; divides $x by $y and assigns the remainder


to $r

$r=$x**$y

Raises $x to the power of $y and assigns the result to


$r

$r=$x<<$n

Shifts bits in $x left $n times and assigns to $r

$r=$x>>$n

Shifts bits in $x right $n times and assigns to $r

$r=++$x

Increments $x and assigns $x to $r

$r=$x++

Assigns $x to $r and then increments $x

$r+=$x;

Adds $x to $r and then assigns to $r

$r=$x

Decrements $x and assigns $x to $r

$r=$x

Assigns $x to $r and then decrements $x

$r=$x;

Subtracts $x from $r and then assigns to $r

$r/=$x;

Divides $r by $x and then assigns to $r

$r*=$x;

Multiplies $r by $x and then assigns to $r

$r=$x<=>$y

$r

is 1 if $x>$y; 0 if $x==$y; -1 if $x<$y

$r=$x||$y

$r

is the logical OR of variables $x and $y

$r=$x&&$y

$r

is the logical AND of variables $x and $y

$r=!$x

$r

is the opposite Boolean value of $x

You can compare values of variables to check results of operations. Table 2.4 lists the
comparison operators for numbers and strings.
Table 2.4. Comparison operations with Perl.
Operation

Description

$x==$y

True

if $x is equal to $y

$x!=$y

True

if $x is not equal to $y

$x<$y

True

if $x is less than $y

$x<=$y

True

if $x is less than or equal to $y

$x>$y

True

if $x is greater than $y

$x>=$y

True

if $x is greater than or equal to $y

$xeq$y

True

if string $x is equal to string $y

$xne$y

True

if string $x is not equal to string $y

$xlt$y

True

if string $x is less than string $y

$xle$y

True

if string $x is less than or equal to string $y

$xgt$y

True

if string $x is greater than string $y

$xge$y

True

if string $x is greater than or equal to string $y

$xx$y

Repeats $x, $y times

$x.$y

Returns the concatenated value of $x and $y

$xcmp$y

Returns 1 if $xgt$y; 0 if $xeq$y; 1 if $xlt$y

$w?$x:$y

Returns $x if $w is true; $y if $w is false

Arrays and Associative Arrays


Perl has arrays to let you group items using a single variable name. Perl offers two types of
arrays: those whose items are indexed by number (arrays) and those whose items are indexed by
a string (associative arrays). An index into an array is referred to as the subscript of the array.
Tip
An associative array is referred to as "hash" because of the way it's stored
internally in Perl.

Arrays are referred to with the @ symbol. Individual items in an array are derived with a $ and the
subscript. Therefore, the first item in an array @count would be $count[0], the second item
would be $count[1], and so on. See Listing 2.2 for usage of arrays.

Listing 2.2. Using arrays.


1#!/usr/bin/perl
2#
3#AnexampletoshowhowarraysworkinPerl
4#
5@amounts=(10,24,39);

6@parts=('computer','rat',"kbd");
7
8$a=1;$b=2;$c='3';
9@count=($a,$b,$c);
10
11@empty=();
12
13@spare=@parts;
14
15print'@amounts=';
16print"@amounts\n";
17
18print'@parts=';
19print"@parts\n";
20
21print'@count=';
22print"@count\n";
23
24print'@empty=';
25print"@empty\n";
26

2.1. What is IP Masquerade?


IP Masquerade is a networking function in Linux similar to the one-to-many (1:Many) NAT
(Network Address Translation) servers found in many commercial firewalls and network routers.
For example, if a Linux host is connected to the Internet via PPP, Ethernet, etc., the IP
Masquerade feature allows other "internal" computers connected to this Linux box (via PPP,
Ethernet, etc.) to also reach the Internet as well. Linux IP Masquerading allows for this
functionality even though these internal machines don't have an officially assigned IP address.
MASQ allows a set of machines to invisibly access the Internet via the MASQ gateway. To other
machines on the Internet, the outgoing traffic will appear to be from the IP MASQ Linux server
itself. In addition to the added functionality, IP Masquerade provides the foundation to create a
HEAVILY secured networking environment. With a well built firewall, breaking the security of a
well configured masquerading system and internal LAN should be considerably difficult to
accomplish.
If you would like to know more on how MASQ (1:Many) differs from 1:1 (true) NAT and Proxy
solutions, please see the Section 7.6 FAQ entry.
2.2. Current Status

IP Masquerade has been in the Linux kernels for several years now and is quite mature as the
kernel enters the 2.4.x stage. Kernels since Linux 1.3.x have had MASQ support built-in. Today,
many individuals and commercial businesses are using it with excellent results.
2.4.x kernel users:

The 2.4.x kernel hosts an entirely re-written set of NAT code which is both far
superior,

You might also like