get Perl for a particular system.
2. Syntax And Variables
The simplest Perl variables are "scalar" variables which hold a single string or number. Scalar
variable names begin with a dollar sign ($) such as $sum or $greeting. Scalar and other
variables do not need to be pre-declared -- using a variable automatically declares it as a global
variable. Variable names and other identifiers are composed of letters, digits, and underscores (_)
and are case sensitive. Comments begin with a "#" and extend to the end of the line.
$x = 2; ## scalar var $x set to the number 2
$greeting = "hello"; ## scalar var $greeting set to the string "hello"
A variable that has not been given a value has the special value "undef" which can be detected
using the "defined" operator. Undef looks like 0 when used as a number, or the empty string ""
when used as a string, although a well written program probably should not depend on undef in
that way. When Perl is run with "warnings" enabled (the -w flag), using an undef variable prints a
warning.
if (!defined($binky)) {
print "the variable 'binky' has not been given a value!\n";
}
What's With This '$' Stuff?
Larry Wall, Perl's creator, has a background in linguistics which explains a few things about Perl. I
saw a Larry Wall talk where he gave a sort of explanation for the '$' syntax in Perl: In human
languages, it's intuitive for each part of speech to have its own sound pattern. So for example, a
baby might learn that English nouns end in "-y" -- "mommy," "daddy," "doggy". (It's natural for a
baby to over generalize the "rule" to get made up words like "bikey" and "blanky".) In some small
way, Perl tries to capture the different-signature-for-different-role pattern in its syntax -- all scalar
expressions look alike since they all start with '$'.
3. Strings
Strings constants are enclosed within double quotes (") or in single quotes ('). Strings in double
quotes are treated specially -- special directives like \n (newline) and \x20 (hex 20) are expanded.
More importantly, a variable, such as $x, inside a double quoted string is evaluated at run-time
and the result is pasted into the string. This evaluation of variables into strings is called
"interpolation" and it's a great Perl feature. Single quoted (') strings suppress all the special
evaluation -- they do not evaluate \n or $x, and they may contain newlines.
$fname = "binky.txt";
$a = "Could not open the file $fname."; ## $fname evaluated and pasted in
-- neato!
$b = 'Could not open the file $fname.'; ## single quotes (') do no
special evaluation
## $a is now "Could not open the file binky.txt."
相关文档
评论