Perl Literals, Variables, and Operators

 

General

 

 

Escape Sequences

Escape sequences are control characters:

 

\a    Bell or a beep

\b      Backspace

\e    Escape

\f    Form feed

\l    Change the next character into lower case

\L    Change all following characters into lowercase

\u    Change the next character into uppercase

\U    Change all following characters into uppercase

\Q    Quote meta-characters as literals

\E    Terminate the \L, \Q, or \U sequence

\\    Back slash

\n      Newline

\r      Carriage return

\t    Tab

\v      Vertical tab

\$    Dollar sign

\@      Ampersand

\0nnn Octal byte number

\xnn  Hexadeciaml byte number

 

 

Literal Constants

      123

      0123

      0x43      -- Hexadecimal number

99.56

 

            If there are two statements in a program:

 

      $currency = 99;

      print "Amount: $currency";

 

            It will access values of variable and display:

 

      Amount: 99

 

 

Literal quotes, will not access values of variable. If there are two statements in a program:

 

      $currency = 99;

      print 'Amount: $currency';

 

            It will access values of variable and display:

 

      Amount: $currency

 

Variables

 

There are three kinds of variables in the Perl:

$address

$first_name

$last_name

@personal_info

 

 

 

Scalar Variables

 

Two scalar variables begins with a dollar sign $ are defined:

$currency   = 100;

$country    = "Taiwan";

$Voltage    = 110;

$Current    = 30;

$HorsePower = 10;

$NumberOfPhase = 3;

$ControlPanels = 20;

$ManulTitle    = "Data Acquisition Card DT330";

 

 

 

 

 

Array variables

 

An array variable starts with the @ sign. It can hold several pieces of data of the same type or different type.  For a regular array, a pair of parentheses ( ) is used to initialized the array and a pair brackets [ ] is used for indexing.

 

Examples: Array initialization and manipulation

 

@numArray = ();   # An empty array

@mixedArray = ("Equipment Name", "Cost", 1000.0, 08, 123);

@number1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

 

 

The array @number1 should hold the same elements as the array @number2:

 

@number2 = (0 .. 9);

 

Two character arrays for holding uppercase letter A, B, C, ..Z and lower case letters:

 

@upchar_array = (A..Z);

@lowchar_array = (a..z);

 

print "@upchar_array \n";      # print all char in the array

print "@upchar_array[0] \n";      # print the first element

print "@upchar_array[25] \n";      # print the last element

 

 

@professors = ("Lin", "Emery", "Broberg", "Leveghetta", "Hack", "Steffen", "Omiston", "Disher");

 

The individual element of the array can then be accessed through the following syntax:

print "Professor : $professors[0]\n";       

print "Professor : $professors[1]\n";     

print "Professor : $professors[5]\n";     

  Results

Professor: Lin

Professor: Emery

Professor: Steffen

 

 

@myarray = ("1",  "two", "three", 4);     

# define an array of that holds data of different types

($first_element, $second_element, $third_element, $fourth_element) = @myarray;

      # assign scalar variables with array's content

@newarray = (0, @myarray, 5);

# now we create a new array with five different elements in

# it: ("0", "1", "two", "three", 4, 5)

 

$last_index = $#array; 

# The index of the last element of the array is 3

$array_size = $last_index +1;

# The number of element in the array is 4 since array index

# starts at 1

$last = @array($#array);

      # Assign the last element of the array into $last variable

 

Perl Expressions and Operators

 

Perl language defines a set of operators that is richer than the C programming language. The meaning of operators and examples are listed below. Assume that four variables used here including $op1, $op2, $op, $num are predefined:

$op1 = 10;

$op2 = 20;

$op = 0;

$num = 4;

 

Special Symbols

 

#     Starts one line comment

&     Added before a name of subroutine when called

$     Scalar variable

@     Array variable

@_    A system parameter array

" "   For quoting a string with variables

' '   For quoting literal string

 

Binary Arithmetic Operators

 

+      Addition operator:      $op = $op1 + $op2; #($op holds 30)

-      Subtraction operator:      $op = $op1 - $op2; #($op holds -10) 

*      Multiplication:         $op = $op1 * $op2; #($op holds 100)

/      Division:               $op = $op1 / $op2; #($op holds 0.5)

%      Remainder or modulus:       $op = $op1 % $op2; #($op holds 10)

**      Exponentiation:         $op = $op1 ** 3;   #($op hold 1000)

 

 

Unary Arithmetic Operators

+      Positive operand: +10

-      Negative operand: -10

++      Increment by 1:

$num = 10;

$op = ++$num;       #pre-increment ($op holds 11)

$op = $num++;       #post-increment ($op holds 10)

--      Decrement by 1:  

$num = 10;

$op = --$num;       #pre-increment ($op holds 9)

$op = $num--;       #post-increment ($op holds 10)

 

Relational Operators

 

==    Equal to

!=    Not Equal to

<     Less than

>      Greater than

<=    Less than or equal to

>=      Greater than or equal to

<=>   Greater than (return 1); Equal to (return 0); Less than

(return -1)

 

 

Logical Operators

&&    AND operator   

||    OR operator   

!     NOT operator   

 

The Bit-Wise Operators

~     Bit-wise NOT:      $op = ~0x01;       #(result 0xFE or 254)

&     Bit-wise AND:       $op = 0x02 & 0x01; #(result 0x00)

|     Bit-wise OR:      $op = 0x02 | 0x01; #(result 0x03)

^     Bit-wise EXOR:      $op = 0x0F ^ 0xF0; #(result 0xFF or 255)

>>    Shift Right:      Shift right one bit is the same as div by 2

$num = 8; $op = $num >> 2; #($op holds 2)

<<    Shift Left:       Shift left one bit is the same as times 2

$num = 8; $op = $num << 2; #($op holds 32)

 

Assignment Operators

=      Assignment

+=    Add and assign

-=    Sub and assign

*=      Multiply and assign

/=    Divide and assign

%=      Remainder and assign

**=      Exponentiation and assign

<<=   Shift left and assign

>>=   Shift right and assign

&=    Bit-wise AND and assign

|=    Bit-wise OR and assign

^=    Bit-wise XOR and assign

 

Relational Operators for String Comparisons

eq    Equal to:               if($op1 eq $op2)

ne    Not Equal to:           if($op1 ne $op2)

lt    Less than:              if("c" lt "b")

le    Less than or equal to:       if("b" le "c"

gt      Greater than:              if("c" gt "b")

ge      Greater than or equal to: if("b" ge "c")

cmp   Greater than (return 1); Equal to (return 0); Less than

(return -1):            if($op1 cmp $op2)

 

 

The Ternary Operator

The conditional statement: if -- else in Perl such as

if(Expession)

Exp1;

else Exp2;

Can be written with the ternary operator:

(Expession?) Exp1: Exp2;

 

The Range operator

..    For defining a range of numbers in the array

      @array = (0 .. 9);  # 0, 1, 2, .., 9

      @letters = ("aa" .. "ae"); # aa, ab, ac, ad, ae

 

 

 

The String Operators

.      Concatenation of strings

      Example:

$newstring = "Amount due " . "=". 30 . "dollars" ;

x      Repetition

      Example:

      $asciinum = "2";

      $numstr   = $asciinum x 4; # $numstr holds "2222"

 

Matching Operator

=~    For testing a string or pattern within a single string of words

 

 

Associative array

 

An associative array is indicated by adding a percent sign, %, in front of a variable name. A pair of parentheses ( ) is used to initialized the array and a pair braces { } is used for indexing. The array is indexed by strings.

 

Examples:

 

# Define a database for saying different HELLO messages

%web_greeting =

 (

   'com', 'hello',    # US Commercial sites

   'edu', 'hi',       # US educational sites

   'mil', 'Sir',      # US military sites

   'fr',  'Bonjour',  # Franch

   'mx',  'hola',     # Maxico

   'tw',  'NeeHou',  # Taiwan

   'jp',  'KonNiChiWa' #Japan

 );

 

 

 

Loop Control Structure

Syntax:

 

if(statement)     # Test the true-false condition of the statement

elseif(statement)      # Placed after the if(statement) to test another

# condition

else(statement)   # Used at the end of if block

 

for(init; endcheck; update)

  {

      statement1;

      statement2;

      }

 

until(condition)  # if true don't execute the statement block

      {

      statement1;

      statement2;

      }

 

do

     {

      statement1;

      statement2;

      } while(condition);

 

while(condition)

      {

      statement1;

      statement2;

      }

 

foreach $var (@array)

      {

      statement1;

      statement2;

      }