Skip to content

Perl Variables

Variable Declaration

Using my to Declare Local Variables

my declares lexically scoped local variables, visible only within the current scope:

perl
use strict;
use warnings;

my $name = "Alice";     # Declare and initialize
my $age;                # Declare without initializing
$age = 25;              # Assign value

{
    my $inner = "inside";  # Only valid within this block
    print "$inner\n";       # Output: inside
}

# print $inner;  # Error: $inner not visible here

Using our to Declare Global Variables

our declares global variables, usable throughout the package:

perl
use strict;
use warnings;

our $global_var = "global";

sub show_global {
    print "$global_var\n";  # Can access
}

show_global();  # Output: global

Using local to Temporarily Modify Variables

local temporarily changes global variable values, restoring original values when scope ends:

perl
use strict;
use warnings;

our $var = "original";

{
    local $var = "modified";
    print "Inside: $var\n";  # Output: modified
}

print "Outside: $var\n";     # Output: original

Variable Scope

Lexical Scope

Variables declared with my have lexical scope:

perl
use strict;
use warnings;

my $x = 10;      # Global lexical variable

sub sub1 {
    my $x = 20;  # Shadows outer $x
    print "sub1: $x\n";  # Output: 20
}

sub sub2 {
    print "sub2: $x\n";  # Output: 10
}

sub1();
sub2();

Dynamic Scope

Variables using local have dynamic scope:

perl
use strict;
use warnings;

our $var = "global";

sub sub1 {
    local $var = "in sub1";
    sub2();
}

sub sub2 {
    print "sub2 sees: $var\n";  # Output: in sub1
}

sub1();
print "main sees: $var\n";      # Output: global

Variable Naming Rules

Naming Rules

perl
# Valid variable names
my $name;
my $user_name;
my $userName;
my $name123;

# Invalid variable names
# my $1name;      # Cannot start with number
# my $user-name;  # Cannot contain hyphen
# my $user name;  # Cannot contain space

Naming Conventions

perl
# Scalars: lowercase, words separated by underscores
my $user_name = "Alice";
my $email_address = "alice@example.com";

# Boolean variables: start with is_ or has_
my $is_valid = 1;
my $has_permission = 0;

# Arrays: plural form
my @users = ("Alice", "Bob", "Charlie");
my @file_names = ("file1.txt", "file2.txt");

# Hashes: plural form or _data suffix
my %user_data = (name => "Alice", age => 25);
my %config = (host => "localhost", port => 8080);

Variable Assignment

Basic Assignment

perl
my $name = "Alice";
my $age = 25;
my $is_valid = 1;

List Assignment

perl
# Assign multiple variables simultaneously
my ($name, $age, $city) = ("Bob", 30, "London");
print "$name, $age, $city\n";  # Bob, 30, London

# Array assignment
my @colors = ("red", "green", "blue");
my ($red, $green, $blue) = @colors;

# Partial assignment
my ($first, $second) = (1, 2, 3, 4, 5);
print "$first, $second\n";  # 1, 2

# Swap variable values
my $a = 10;
my $b = 20;
($a, $b) = ($b, $a);
print "a=$a, b=$b\n";  # a=20, b=10

Hash Assignment

perl
my %person = (
    name => "Alice",
    age => 25,
    city => "New York"
);

# Add key-value pair
$person{email} = "alice@example.com";

# Modify value
$person{age} = 26;

Default Values

undef Value

Uninitialized scalar values are undef:

perl
use strict;
use warnings;

my $value;
print defined($value) ? "defined" : "undef";  # Output: undef

# In numeric context, undef becomes 0
my $num = $value + 10;  # $num = 10

# In string context, undef becomes empty string
my $str = "value: " . $value;  # $str = "value: "

Setting Default Values

perl
# Use || operator
my $name = $input_name || "Anonymous";

# Use //= operator (Perl 5.10+)
my $email //= "no-email@example.com";

# Use defined-or operator
my $age = defined($user_age) ? $user_age : 0;

# Using default parameters in functions
sub greet {
    my ($name, $greeting) = @_;
    $name //= "World";
    $greeting //= "Hello";
    print "$greeting, $name!\n";
}

Special Variables

Default Variable $_

perl
# In loops
foreach (1..5) {
    print;  # Same as print $_
}

# In pattern matching
$_ = "Hello World";
/World/;  # Same as $_ =~ /World/

# Default input
while (<STDIN>) {
    print;  # Output read line
}

List Separator $"

perl
$" = ", ";  # Set separator for array interpolation
my @array = (1, 2, 3);
print "@array\n";  # Output: 1, 2, 3

Input Record Separator $/

perl
$/ = "";  # Paragraph mode
$/ = "\n"; # Line mode (default)

# Read entire file
$/ = undef;
my $content = <FILE>;

Output Record Separator $\

perl
$\ = "\n";  # Automatically add newline
print "Hello";  # Output: Hello\n

Output Field Separator $,

perl
$, = ", ";
print "a", "b", "c";  # Output: a, b, c

Variable References

Creating References

perl
# Scalar reference
my $scalar = 42;
my $scalar_ref = \$scalar;
print $$scalar_ref;  # Output: 42

# Array reference
my @array = (1, 2, 3);
my $array_ref = \@array;
print @$array_ref;   # Output: 123

# Hash reference
my %hash = (name => "Alice");
my $hash_ref = \%hash;
print $hash_ref->{name};  # Output: Alice

# Anonymous array reference
my $anon_array = [1, 2, 3];

# Anonymous hash reference
my $anon_hash = {name => "Bob", age => 30};

Dereferencing

perl
# Method 1: Use $ and @ or %
my $array_ref = [1, 2, 3];
my @array = @$array_ref;

# Method 2: Use arrow operator
my $first = $array_ref->[0];  # Access first element

# Hash dereferencing
my $hash_ref = {name => "Alice"};
my %hash = %$hash_ref;
print $hash_ref->{name};  # Output: Alice

Constants

Using constant

perl
use constant {
    PI => 3.14159,
    MAX_USERS => 100,
    API_KEY => "abc123"
};

print PI;           # Output: 3.14159
print MAX_USERS;    # Output: 100
# PI = 3.14;        # Error: Cannot modify constant

Using Readonly

perl
use Readonly;

Readonly my $PI => 3.14159;
Readonly my @DAYS => qw(Monday Tuesday Wednesday);
Readonly my %CONFIG => (host => "localhost", port => 8080);

print $PI;           # Output: 3.14159
print @DAYS;         # Output: MondayTuesdayWednesday

Practice Examples

Example 1: Variable Scope Demonstration

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

my $global = "global scope";

sub demo_scope {
    my $local = "local scope";
    print "Inside sub: $global, $local\n";
}

demo_scope();          # Output: Inside sub: global scope, local scope
print "Outside sub: $global\n";
# print $local;        # Error: $local not visible here

Example 2: Using References

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

# Create array of hashes
my @users = (
    {name => "Alice", age => 25},
    {name => "Bob", age => 30},
    {name => "Charlie", age => 35}
);

foreach my $user (@users) {
    printf "%-10s: %d years old\n", $user->{name}, $user->{age};
}

Example 3: Default Value Handling

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

sub get_user_info {
    my ($name, $email, $age) = @_;

    $name //= "Unknown";
    $email //= "no-email@example.com";
    $age //= 0;

    return {
        name => $name,
        email => $email,
        age => $age
    };
}

my $info1 = get_user_info("Alice");
my $info2 = get_user_info("Bob", "bob@example.com");
my $info3 = get_user_info("Charlie", "charlie@example.com", 25);

foreach my $info ($info1, $info2, $info3) {
    printf "Name: %-10s Email: %-20s Age: %d\n",
           $info->{name}, $info->{email}, $info->{age};
}

Summary

In this chapter, we learned Perl variables:

  1. ✅ Variable declarations (my, our, local)
  2. ✅ Variable scope (lexical, dynamic)
  3. ✅ Variable naming rules and conventions
  4. ✅ Variable assignment and default values
  5. ✅ Special variables and references
  6. ✅ Constant definitions

Next, we will learn Perl Operators.

Content is for learning and research only.