|
||||
|
|
Perl Variables and Data Types
What is a variable?Put simply, a variable is a container that holds a numeric or string value. The most common container for storing information in Perl is the scalar. Here's a very simple Perl program that demonstrates a scalar: #!/usr/bin/perl -w use strict; my $num_apples; $num_apples = 5; Let's examine this program line by line. The first line is required to let the system know where to find the Perl interpreter on your system. On most UNIX/Linux and MacOSX systems, it is found at "/usr/bin/perl" in the filesystem. Please note: the "#!" characters are required before the full path to Perl. On Windows systems, Perl most likely lives at "C:\perl\bin\perl.exe". If in doubt, consult the documentation for your version of Perl. Continuing on, the "-w" after the path to Perl tells the interpreter to turn on warnings. This is generally a good idea, as potential problems with your programs will be mentioned when you run them. The "use strict;" line tells Perl to turn on strict mode, which requires that all variables and data structures be declared with the "my" statement before they can be used in your program. This eliminates the potential for sneaky typographical errors to create mysterious bugs. Getting to the "meat" of our program, the line "my $num_apples;" declares a scalar variable named "num_apples" (the "$" character tells Perl that the variable is a scalar). The last line in the program assigns a value of "5" to "num_apples". Notice that each statement in our program ends with a colon character. This lets Perl know that each statement is finished, and reflects the influence of languages such as C and C++ on Perl's syntax. To run these examples, copy and paste the source code into your favorite editor, and save it as a file with a ".pl" extension. If you're on a UNIX-based system, you'll need to make the script executable by issuing the command "chmod +x yourscript.pl" (where "yourscript.pl" is the name of your program). Run the script by typing "./yourscript.pl" at your shell prompt. If you're running Windows, execute the script from a command prompt by typing "perl yourscript.pl".
Variable Typing and Basic OperationsIn most programming languages, you have to tell the compiler that a variable is destined to hold a specific type of data (hence the term "data type"). In the C language, variables can be int (for integers), char (for characters), and so on. Perl doesn't require you to decide ahead of time what kind of data your variable will store, leaving it up to you to know how to do the right thing for your goal. Let's look at another example involving simple arithmetic: #!/usr/bin/perl -w use strict; my $num1; my $num2; my $total; $num1 = 5; $num2 = 10; $total = $num1 + $num2; print $total . "\n"; pparadis@ubuntu-devel:~$ ./example.pl 15 Running this example should display the number "15" on your screen. We declare three scalars: two to hold numbers to be added, and a third to hold the sum. The "print" command tells the program to print the output to STDOUT (standard output), which is your screen by default. This code sums the values held in $num1 and $num2; let's look at an example which concatenates the values instead: #!/usr/bin/perl -w use strict; my $num1; my $num2; my $total; $num1 = 5; $num2 = 10; $total = $num1 . $num2; print $total . "\n"; pparadis@ubuntu-devel:~$ ./example.pl 510 Run this program, and you'll notice that the output changes to "510". Odd, huh? Astute observers will note that we changed only one character from the preceding example, swapping out the "+" operator for a "." character. This tells Perl to treat the values stored in $num1 and $num2 as strings (a list of characters), and to concatenate (push together) the values into $total. Remember, Perl doesn't care what you're storing in your scalars. What matters is the operator you use to perform an operation on the data. Here's an example that demonstrates a more practical use of string concatenation: #!/usr/bin/perl -w use strict; my $first_part; my $second_part; $first_part = "Lisa is going "; $second_part = "to the store."; print $first_part . $second_part . "\n"; pparadis@ubuntu-devel:~$ ./example.pl Lisa is going to the store. This code should show the sentence "Lisa is going to the store." on your screen. Notice that we didn't store the concatenated value in a separate scalar; you can use the print function to do the work for you. Now, since Lisa is going to the store, she probably needs a shopping list. Let's help her make one using something called an "array", which is a list of data items. Lists of Data Items: ArraysLet's say you have a list of items you want stored in a data structure in Perl. You can use a simple array to get the job done:
#!/usr/bin/perl -w
use strict;
my @grocery_list;
@grocery_list = ("apples\n", "oranges\n", "milk\n", "bread\n");
print @grocery_list;
pparadis@ubuntu-devel:~$ ./example.pl apples oranges milk bread Each item should be shown on a separate line when you run the program. We've added "\n" to the end of each food to make sure we have a line break after each one is printed. Using the "@" symbol instead of "$" tells Perl that the "grocery_list" is to be treated as an array. Arrays in Perl are 0-based, which is to say that the first entry is referred to an the "0th" item. This is one respect in which Perl differs from some languages (such as BASIC), which treat arrays as starting with "1" instead. Now, what if we want to view only the third item in the list? Add this line of code to the last example program: print $grocery_list[2]; Wait just a minute! Before, I told you that arrays are referred to my the "@" character. I've just used a "$" character here! When referring to an individual element of an array, this convention is used, along with the number of the index you want to use in brackets. This is because a simple array is a list of scalars, which are referred to by the "$" character. Remember that since arrays in Perl are zero-based, the third item is stored in index two of the array. Hashes in PerlSometimes you need more flexibility than simple scalars or arrays can offer. Perl supports the "hash" data structure, which allows you to refer to other data structures by a key->value relationship. When declaring a hash, the "%" character is used. Let's see an example:
#!/usr/bin/perl -w
use strict;
# Declare a hash named "person".
my %person;
# Tell Perl all about Fred.
$person{"name"} = "Fred";
$person{"age"} = 25;
$person{"height"} = 72;
$person{"weight"} = 150;
print "The person's name is " . $person{"name"} . ".\n";
pparadis@ubuntu-devel:~$ ./example.pl The person's name is Fred. I've used this program to introduce a new concept: comments. When you write a program, it's very helpful to have a way to remind yourself what each section of code does, and comments are the standard way of doing this. When Perl sees the "#" symbol at the start of a line, it stops processing that line (with the exception of the first line of the program) and moves on. This allows you to greatly improve the readability of your code, and helps others make changes to it in the future. In this code, the keys are named "name", "age", etc. The values are assigned to each key, allowing you to store all sorts of information about Fred in a single place. Hashes are often very useful for representing data from a database (we'll get to that later), or for organizing information loaded from a file. Perl allows you to have more advanced data structures than those shown in this chapter; you can have arrays of arrays, multi-dimensional arrays, arrays of hashes, hashes of arrays of hashes, and so on. These are more advanced topics better reserved for a time when you've become more comfortable with the language. The next chapter introduces program flow control, which allows you to do more useful things with your programs. Continue: Program Flow Control Table of Contents
|
|||
| All contents Copyright © 2007-2011 ClassHelper.org®. Please see our Privacy Policy. | ||||