Scalars and sigils
| The dollar sigil | |
| my and lexical scope | |
| Naming rules | |
| undef and defined | |
| our and package variables |
The dollar sigil
A Perl variable name always carries a sigil, a punctuation mark that says what kind of value the name holds. The dollar sign marks a scalar: one value, whether it is a number, a string or a reference.
my $name = "Ada";
my $age = 36;
print "$name is $age\n"; # prints Ada is 36
perl demo.pl
Ada is 36
The sigil is part of the name, not decoration: $name and @name are two unrelated variables. Lesson 9 explains the at sign, which marks an array.
my and lexical scope
my declares a variable for the current block. The name disappears at the closing brace, which keeps large programs from leaking state between unrelated pieces of code.
Without use strict Perl would let you assign to an undeclared name; with it, a typo such as $nmae becomes an error at compile time instead of a silent bug at runtime.
my $count = 0;
{
my $count = 10; # inner copy, outer stays 0
print "inner $count\n";
}
print "outer $count\n"; # prints 0
perl demo.pl
inner 10
outer 0
Naming rules
After the sigil a name starts with a letter or an underscore, then uses letters, digits and underscores. Lower case with underscores for word breaks is the common style, the same snake_case that Perl inherited from the C world.
Names may be long. Write $files_processed rather than $fp, and the reader of your program will thank you.
my $first_name = "Ada";
my $_score2 = 10;
print "$first_name\n";
perl demo.pl
Ada
undef and defined
A declared variable with no value holds undef, the absence of a value. Printing it gives an empty string and warns under use warnings, which is usually the first sign of a missing assignment.
Test with defined before you use a value that may be missing. The // operator (defined-or) supplies a fallback in one expression:
my $nick;
print "missing\n" unless defined $nick;
$nick //= "guest";
print "$nick\n"; # prints guest
perl demo.pl
missing
guest
Defined-or differs from the logical or operator: || also replaces an empty string and a zero, while // only replaces an undefined value.
our and package variables
our declares a name that belongs to the current package instead of the current block. You will see it in older code and in modules that export globals; for new code, prefer a lexical my and pass values as arguments.
our $VERSION = "1.00";
print "version $main::VERSION\n";
perl demo.pl
version 1.00
The full name of a package variable is $main::VERSION: package name, double colon, bare name. A lexical my variable has no such full name, which is one reason it is safer.
Next: Numbers
Article author: Arthur Isaev