Basic Perl Syntax Guide - Variables: scalars, arrays, hashes.

 

Before we begin discussing variables in perl, we need to mention comments.  A comment is any line that begins with a pound sign.  It is ignored by the perl interpreter and is used to describe certain parts of code.

 

For instance:

 

# this is a comment

my $this_is_a_variable_definition = ‘some value’; # here is another comment

print $this_is_a_variable_definition;

 

There are three primary data structures in perl: the scalar, the array, and the associative array, or “hash”.

 

The scalar:

 

The scalar can hold one specific piece of information at a time, such as a string, integer, or reference.  For now, we’ll just focus on strings and integers, as references are outside the scope of this lesson.

 

Strings:

 

Strings are any sequence of characters that you want to store and/or manipulate.

 

You define a string using a dollar like this in perl:

 

my $string = ‘some value’;

 

Note: Whenever you first define either a scalar, array, or hash, use the my keyword to denote that it belongs to a particular scope.  This will save you many many bugs in the future.

 

All variables, whether they be a scalar, array, hash, or other type, are CASE-SENSITIVE, meaning that $myvariable and $MYVARIABLE are treated as two different variables.

 

Scope is a particular area inside opening and closing brackets, and defines where a variable is accessible from.

 

Consider the following code:

 

my $string = ‘David’;

{

  $string = ‘John’;

}

print $string; # this will print the text “John”

 

my $string = ‘David’;

{

  my $string = ‘John’;

}

print $string;

 

This code will produce an error, because you attempted to use the my keyword on a variable that has already been defined.

 

$string = ‘David’;

print $string;

 

This will also produce an error because you did not define the scalar variable $string yet using the my keyword.

 

{

  my $string = ‘John’;

}

print $string;

 

This will produce an error too because the scalar variable $string is not defined in the same scope as the print statement used to print the value of that variable.

 

my $string = ‘David’;

{

  $string = ‘John’;

}

print $string; # this will print the text “John”

 

my $string = ‘David’;

{

  my $string = ‘John’;

  print $string; # this will print the text “John”

}

print $string; # this will print the text “David”

 

Starting to make sense now?

 

If you use a single quote, anything you put in the scalar definition goes in just like you typed it.  However, if you use a double quote, variables are “interpolated” inside the variable definition.

 

For instance:

 

my $text = ‘cool guy’;

my $string = ‘some $text’;

print $string; # prints literally “some $text”;

 

my $text = ‘cool guy’;

my $string = “some $text”;

print $string; # prints literally “some cool guy”;

 

If you are putting an email address inside a string and use double quotes, you need to use a backslash in front of the @ sign to say to perl ‘this is not a variable to interpolate’, or perl will produce an error.

 

For instance:

 

my $email = ‘david@somehost.net’;  # fine – no error

my $email = “david@somehost.net”; # will produce an error message

my $email = “david\@somehost.net”; # fine – no error

 

You also have to put a backslash in a string when you put a single or double quote in the string.

 

For instance:

 

My $string = “this is a “bad” string”; # will produce an error

My $string = “this is a \”good\” string”; # will not produce an error

My $string = “this is a ‘good’ string; # will not produce an error

My $string = ‘this is a ‘bad’ string’; # will produce an error

My $string = ‘this is a \’good\’ string’; # will not produce an error

My $string = ‘this is a “good” string’; # will not produce an error

 

Now that you know how to create strings, let’s teach you how to do various testing on strings.

 

To find a strings length:

 

$string = ‘some string’;

my $string_length = length($string);

# value of $string_length is now ‘11’

 

To find if a string contains a certain character or string of characters:

 

if($string =~ /some/)

{

  print ‘string contains the word some!’;

}

else

{

  print ‘string does not contain the word some!’;

}

 

To split up a string into an array, use split

 

my $string_to_split = ‘this is a sentence’;

 

my @array = split(/ /, $string_to_split);

 

then you can loop through the values like so:

 

(see below in the next section for more info on control structures like foreach)

 

foreach my $value (@array)

{

  print $value . “\n”;

}

 

this prints:

 

--

this

is

a

sentence

--

 

Another way of using the split function is defining specific named scalars, as in

my $string_to_split = ‘this is a sentence’;

my($first_variable, $second_variable, $third_variable, $fourth_variable) = split(/ /, $string_to_split);

 

print <<SOME_STUFF;

first variable value: $first_variable

second variable value: $second_variable

third variable value: $third_variable

fourth variable value: $fourth_variable

SOME_STUFF

 

The above code prints out:

 

--

first variable value: this

second variable value: is

third variable value: a

fourth variable value: sentence

--

 

The split function takes two arguments.  In perl, when you pass a function variables to process, they are called “arguments”.  The first argument is a “regular expression” (don’t worry about that for now) which defines how to split up the text.  For now, just think of this in terms of having a specific character that breaks up the boundaries of the string you want to chop up in to pieces.  The second argument is the variable that you actually want to split.

 

In the above example, I touched on another usage of the print function, called the “multiline print operator”.  If you type print, then two less than signs, then any string of text, then a semi-colon, you can type as much text as you want into your script, which will have variables interpolated for you.  Then all you do is type the same string of text you used in the beginning to end this multiline print operator.  Be careful though, if the second string of text is not flush to the left margin of your file, perl will print an error.

 

Here’s another look:

 

print <<SOME_TEXT_I_WANT_TO_PRINT;

 

Here is my text here!

 

This is neat stuff.<p>

 

I can include html easily in multiline print operators.<p>

 

<a href=”mailto:david@somehost.com”>send me an email!</a>

 

SOME_TEXT_I_WANT_TO_PRINT

 

This will print the above text out to the browser.  However, if you type it like this:

 

print <<SOME_TEXT_I_WANT_TO_PRINT;

 

Here is my text here!

 

This is neat stuff.<p>

 

I can include html easily in multiline print operators.<p>

 

<a href=”mailto:david@somehost.com”>send me an email!</a>

 

                        SOME_TEXT_I_WANT_TO_PRINT

 

Then your script will produce an error because the closing identifier to the multiline print operator is not flush with the left margin.

 

String Concatenation:


Another thing we saw above inside the foreach statement was string contatenation.  This is simply a fancy word for joining together two variables.

 

Consider this code:

 

my $string1 = ‘I would like to ‘;

my $string2 = ‘go to a movie ‘;

my $string3 = ‘some time before tomorrow.’;

my $final_string = $string1 . $string2 . $string 3;

print $final_string; # this literally prints “I would like to go to a movie some time before tomorrow.”

 

So, in summary, string concatenation in perl is where you use a period to join together scalar variable strings into a longer scalar variable string.  When you use concatenation, you need to assign the resulting longer string to a new string, which in our example is named $final_string.  Also, keep in mind that if you concatenate an integer (see below) with a string, they are no longer integers.  This is because you can’t perform math operations on a ‘p’ character!

 

One final thing we saw above is “\n”. This is a “newline character”.  This will make a new line print out in the html document we are dynamically generating.  If you look at this text here:

 

--

I

Am

Writing

Text

--

 

you’ll see that what is separating the words is a newline.  Other useful “escape sequences” as they’re called, are “\t” (tab), and “\r” (carriage return). 

 

Integers:

 

Integers in perl are simply numbers, and are the second type of scalar variable I’m going to talk about.  You define integers the same way as you do strings, however you don’t need quotes.  You can use quotes though if you want, perl will figure out what it is depending on what you’re doing with the variable.

 

my $integer = 1;

print $integer; # prints “1”

 

An easy way to increment (add 1 to) a scalar variable that is an integer is to use the ++ operator.

 

For instance:

 

my $integer = 1;

$integer++;

print $integer; # prints “2”

 

Performing basic math on integers:

 

Addition:

 

my $first_integer = 1;

my $second_integer = 2;

my $third_integer = $first_integer + second_integer;

print $third_integer; # prints “3”

 

Subtraction:

 

my $first_integer = 1;

my $second_integer = 2;

my $third_integer = $first_integer - second_integer;

print $third_integer; # prints “-1”

 

Division:

 

my $first_integer = 1;

my $second_integer = 2;

my $third_integer = $first_integer / second_integer;

print $third_integer; # prints “.5”

 

Note: Perl produces an error if you divide by zero.

 

Multiplication:

 

my $first_integer = 1;

my $second_integer = 2;

my $third_integer = $first_integer * second_integer;

print $third_integer; # prints “2”

 

 

Arrays:

 

Arrays are simply a list of scalar variables.  Arrays begin with an @ sign instead of a dollar sign.

 

For instance, here is how we create an array in perl:

 

my @array = (“string 1”, “string 2”, “string 3”);

 

The opening and closing parentheses are required here.

 

To access the values in an array, you can use a foreach statement (see below), or reference the array elements directly.  The array “index”, or number of elements, begins with 0.  So the following code:

 

my @array = (“string 1”, “string 2”, “string 3”);

Print $array[0] . “\n”;

Print $array[1] . “\n”;

Print $array[2] . “\n”;

 

Prints out the following:

 

--

string 1

string 2

string 3

--

 

So when you’re referencing an individual element of an array, you use a dollar sign, not the @ sign.

 

Hashes (aka. “Associate Arrays”)

 

A hash is a list of name value pairs.

 

To define a hash, use this syntax (the percent sign):

 

my %hash;

 

To add new values to a hash, use this syntax:

 

my %hash;

$hash{‘key1’} = ‘value1’;

$hash{‘key2} = ‘value2’;

$hash{‘key3’} = ‘value3’;

 

The keys and values are simply scalar variables.

 

To access hash elements, simply reference the hash key name.  Here’s an example:

 

my %hash;

$hash{‘key1’} = ‘value1’;

print $hash{‘key1’}; # prints “value1”

 

To loop through all elements in a hash, using a while loop and the each function is my preferred way (see below for more info on control structures like “while”):

 

$hash{‘key1’} = ‘value1’;

$hash{‘key2} = ‘value2’;

$hash{‘key3’} = ‘value3’;

while (my($key, $value) = each(%hash))

{

  print $key . ‘ – ‘ . $value . “\n”;

}

 

prints:

 

--

key1 – value1

key2 – value2

key3 – value3

--

 


<-- Previous: Introduction To CGI | Next: Basic Perl Syntax Guide � Control Structures and Conditional Statements -->


Please rate this cgi tutorial on cgi-resources.com:

CGI-Resources Rating:


Ecommerce Shopping Cart Software
ShopCMS Paypal Shopping Cart
Free CGI Scripts
CGI Tutorial
Software Engineering Consultant
Search Engine Optimization Tips
How To Choose Quality Web Hosting
Free Search Engine Ranking Software
HTTP Compression
Install CGI Scripts
Tell A Friend Script
LittleFTP Free FTP Client For Windows


Link To
This Page!


Copy the following code and paste it into your html file.
Ecommerce Shopping Cart Software | ShopCMS Paypal Shopping Cart | Software Engineering Consultant | Free Search Engine Ranking Software | HTTP Compression | Install CGI Scripts | Search Engine Optimization Tips | CGI Tutorial | CGI Scripts | How To Choose Quality Web Hosting | Tell A Friend Script