You start your exploration of Perl by looking at simple, single-value variables. Next you use these variables in some basic expressions. Almost all the concepts discussed here have equivalents in C, so learning them should not be too difficult.
Unlike most other languages, Perl doesn’t have different variable types. There is only one type of data in Perl: the string. Perl lets you use numbers, but as far as Perl is concerned what you really have is a string of digits. Want to deal with characters? Then you’re dealing with one-character strings. Want to handle binary? Then you’re dealing with a string of 1s and 0s.
To declare a variable in Perl, use the directive my:
my $size = 42; # The size of the box in inches
Take a close look at this statement. The statement begins with the keyword my indicating a local variable declaration. (You learn about global variables in Chapter 7, “Subroutines and Modules.”) The name of the variable is $size. The dollar sign ($) indicates that this is a scalar variable. In other words, it holds a single value.
This statement initializes the value of the variable to 42. Because Perl is a string-oriented language, this is actually a two-character string. In fact, you could have written the statement as
my $size = "42"; # The size of the box in inches
Finally there is a comment. In Perl, comments begin with a hash mark (#) and continue to the end of the line.
If you do not initialize a variable, it is assigned the special value undef. This value is different from the empty string (""). If you try to use an initialized variable for comparison, printing, or arithmetic, Perl issues a warning (of course the warning is only issued if you turned on warnings with the use warnings statement or the –w flag). For example:
Use of uninitialized value at <file> line <line>.
Now see how you can use variable declarations in a simple program. On the weekends, I’m a real engineer at the Poway-Midland Railroad. A co-worker asked me how much power the locomotive produced. Listing 2.2 is a Perl program that answers this question.
The steam engine has 16-inch cylinders and operates at 120PSI.
use strict; use warnings; my $cylinder = 16; # Cylinder size is 16 inches (diameter) my $pressure = 120; # Operating pressure in PSI # Pressure at the cross head using the famous pi r <squared> my $effort = 3.14159 * ($cylinder / 2.0) ** 2; print "Total pressure on the cylinder $effort "; |
This program introduces a couple of things. First is the exponent operator (**).
Second, when Perl sees a string enclosed in double quotes ("), it interprets any variables it finds in it. So when you tell Perl to print the answer, it looks through the string for any dollar signs. If it sees any, it performs variable substitution. If you want to put a dollar sign ($) inside a print statement, you need to escape it. For example:
print "Total cost $5,000 ";
prints
Total cost $5,000
Declare a Variable AnywherePerl lets you declare a variable anywhere. The scope of the variable is from the point it is declared to the end of the file. If the variable is declared inside a curly bracket block ({}), the scope of the variable ends at the end of the block. |
Perl and C share a common set of operators. All the C arithmetic operators do the same thing in Perl. These operators include the following:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
< Left Shift
>> Right Shift
++ Increment
-- Decrement
| Bitwise or
& Bitwise and
^ Bitwise exclusive or
~ Bitwise not (invert)
?: Conditional
In addition, Perl has a few new operators that C does not. These are
. String concatenation
my $full_name = $first . " " . $last; # See note below
** Exponentiation
my $gross = 12**2
x Repeat (Repeats a string a given number of times)
my $no = "no " x 3; print "$no "; # prints "no no no"
The expression:
my $full_name = $first "" $last;
So when it comes to arithmetic, Perl is not that much different from C. However, Perl’s power comes from what it can do with strings, as you’ll see in later chapters.
There’s one type of expression that you haven’t learned about yet—the expressions evaluated when a string is interpreted. For example, the statement
my $full_name = "$first $last";
A number of characters have special meaning inside double quotes ("). These are the scalar variable names, which begin with $, array names, which begin with @ (more on this in Chapter 3, “Arrays”), and escape sequences, which start with .
For example:
my $size = 42; # Size of a dimension my $name = "width"; # Name of the dimension my $title = "$name $size";
In this case, the value of $title is assigned the following value:
width<tab>42
But what happens if you want to put text after a variable name? Suppose that you want to say “42inches” rather than just “42.”You can’t write the expression as
my $title = "$name $sizeinches";
This won’t work because Perl looks for a variable called $sizeinches. The solution is to separate the variable from the rest of the string by enclosing the name in curly brackets ({}) as follows:
my $title = "$name ${size}inches";
If you don’t want Perl to interpolate your strings, use single quotes ('). The only things that Perl considers special inside single quotes are the escape characters ' and \.
For example:
print 'The amount is 800 ($HK) 100 ($US) ';
WarningThe previous example contains an error: The author expected the escape to print a newline. Because Perl does not interpret things inside single quotes (except ’ and \), does not print newline. Instead it prints “backslash n.” |
Perl lets you define numbers using the same syntax rules as C. Octal numbers begin with “0”, hexadecimal numbers with “0x”, and floating point numbers use a decimal point, or the “E” notation (for example, 1E33). Hexadecimal numbers begin with a zero and a lowercase x. The prefix 0X does not signify a hexadecimal number.
Perl does allow you to use the underscore in numbers if you want. For example:
my $cost = 1_333_832; # Something costs a lot
Now that you’ve got variables, constants, and expressions down, you can look at I/O and control statements.