BudiBadu Logo
Samplebadu

Perl by Example: Scalars

Perl 5

Working with single values through this sample code demonstrating scalar variable declaration with dollar sign sigil, automatic type conversion between strings and numbers, string interpolation in double quotes, and undefined value handling.

Code

#!/usr/bin/perl
use strict;
use warnings;

# Scalar variables start with $
my $name = "Camel";
my $version = 5.34;
my $is_active = 1;

# String interpolation
print "Language: $name, Version: $version\n";

# Basic operations
my $next_version = $version + 0.1;
my $greeting = "Hello " . $name; # Concatenation

# Undefined scalar
my $empty;
if (!defined($empty)) {
    print "Variable is undefined\n";
}

Explanation

Scalars are Perl's fundamental data type, holding a single value which can be a number (integer or floating-point), a string of characters, or a reference to another data structure. Scalar variable names are prefixed with the dollar sign $ sigil. Perl performs automatic type conversion between numbers and strings based on context, treating values as numbers in mathematical operations and as strings in concatenation or pattern matching.

Scalar characteristics include:

  • String interpolation occurs in double quotes "...", expanding variables inline
  • Single quotes '...' preserve literal text without variable expansion
  • The dot operator . concatenates strings, distinct from + for addition
  • The defined() function tests if a scalar has been assigned a value
  • Scalars can hold references created with backslash \ operator

The use strict; pragma enforces variable declaration with my, our, or state, preventing accidental global variables. The use warnings; pragma enables helpful warnings about potential issues like using undefined variables or ambiguous syntax. These pragmas are considered essential for writing maintainable Perl code and catching bugs during development.

Code Breakdown

6
my $name = "Camel" declares lexical scalar with $ sigil.
11
Double quotes enable string interpolation, expanding $name and $version.
15
. dot operator concatenates strings, + would attempt numeric addition.
19
defined() returns true if scalar has been assigned a value.