Perl Language Variables Scalars


Example

Scalars are Perl's most basic data type. They're marked with the sigil $ and hold a single value of one of three types:

  • a number (3, 42, 3.141, etc.)
  • a string ('hi', "abc", etc.)
  • a reference to a variable (see other examples).
my $integer = 3;                      # number
my $string = "Hello World";           # string
my $reference = \$string;             # reference to $string

Perl converts between numbers and strings on the fly, based on what a particular operator expects.

my $number = '41';                    # string '41'
my $meaning = $number + 1;            # number  42
my $sadness = '20 apples';            # string '20 apples'
my $danger = $sadness * 2;            # number '40', raises warning

When converting a string into a number, Perl takes as many digits from the front of a string as it can – hence why 20 apples is converted into 20 in the last line.

Based on whether you want to treat the contents of a scalar as a string or a number, you need to use different operators. Do not mix them.

# String comparison                   # Number comparison
'Potato' eq 'Potato';                 42 == 42;
'Potato' ne 'Pomato';                 42 != 24;
'Camel'  lt 'Potato';                 41 < 42;
'Zombie' gt 'Potato';                 43 > 42;

# String concatenation                # Number summation
'Banana' . 'phone';                   23 + 19;

# String repetition                   # Number multiplication 
'nan' x 3;                            6 * 7;

Attempting to use string operations on numbers will not raise warnings; attempting to use number operations on non-numeric strings will. Do be aware that some non-digit strings such as 'inf', 'nan', '0 but true' count as numbers.