Perl Data Types
Overview
Perl is a weakly typed language but has three main data types:
- Scalars: Store single values
- Arrays: Store ordered lists of values
- Hashes: Store key-value pairs
Each data type has its unique sigil:
- Scalars:
$ - Arrays:
@ - Hashes:
%
Scalars
Scalar Value Types
Scalars can store the following types of values:
perl
use strict;
use warnings;
# Numbers
my $integer = 42; # Integer
my $float = 3.14; # Floating point
my $scientific = 1.23e-4; # Scientific notation
# Strings
my $string1 = "Hello"; # Double-quoted string
my $string2 = 'World'; # Single-quoted string
my $empty = ""; # Empty string
# Special values
my $undef = undef; # Undefined value
my $true = 1; # True value
my $false = 0; # False value
# References
my $array_ref = [1, 2, 3]; # Array reference
my $hash_ref = {a => 1, b => 2}; # Hash referenceDouble vs Single Quotes
perl
my $name = "Alice";
# Double quotes: interpolate variables and escape sequences
print "Hello, $name\n"; # Output: Hello, Alice
print "Tab\tNewline\n"; # Output: Tab Newline
# Single quotes: literal, no interpolation
print 'Hello, $name\n'; # Output: Hello, $name\n
print 'Tab\tNewline\n'; # Output: Tab\tNewline\nString Operations
perl
# String concatenation
my $first = "Hello";
my $second = "World";
my $combined = $first . " " . $second; # Use dot operator
print $combined; # Output: Hello World
# String repetition
my $dashes = "-" x 10;
print $dashes; # Output: ----------
# String length
my $str = "Hello";
my $length = length($str);
print "Length: $length\n"; # Output: Length: 5
# Substring
my $substring = substr($str, 1, 3); # Start at position 1, take 3 characters
print $substring; # Output: ell
# Case conversion
print uc($str); # Output: HELLO
print lc($str); # Output: hello
print ucfirst($str); # Output: Hello (first letter uppercase)Arrays
Creating Arrays
perl
# Empty array
my @empty = ();
# Create from list
my @numbers = (1, 2, 3, 4, 5);
my @fruits = ("apple", "banana", "orange");
# Use qw for simplicity
my @colors = qw(red green blue yellow);
my @days = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
# Use range
my @range1 = (1..10); # 1 to 10
my @range2 = ('a'..'z'); # a to z
my @range3 = (1..5, 10..15); # Mixed rangeAccessing Array Elements
perl
my @numbers = (10, 20, 30, 40, 50);
# Access single element (use $ prefix)
print $numbers[0]; # Output: 10
print $numbers[2]; # Output: 30
print $numbers[-1]; # Output: 50 (last element)
# Access multiple elements (slice)
my @subset = @numbers[1, 3]; # (20, 40)
my @slice = @numbers[0..2]; # (10, 20, 30)Array Operations
perl
my @numbers = (1, 2, 3);
# Add elements
push @numbers, 4; # Add at end: (1, 2, 3, 4)
unshift @numbers, 0; # Add at beginning: (0, 1, 2, 3, 4)
# Remove elements
my $last = pop @numbers; # Remove and return last: (0, 1, 2, 3)
my $first = shift @numbers; # Remove and return first: (1, 2, 3)
# Array length
my $count = scalar @numbers; # Returns 3
print $#numbers; # Returns last index: 2
# Delete elements
delete $numbers[1]; # Delete index 1, keep position: (1, undef, 3)
splice @numbers, 1, 1; # Delete index 1, no position: (1, 3)
# Sort
my @sorted = sort @numbers; # Alphabetical sort
my @numeric_sorted = sort { $a <=> $b } @numbers; # Numeric sort
# Reverse
my @reversed = reverse @numbers; # (3, 2, 1)Array Iteration
perl
my @fruits = ("apple", "banana", "orange");
# Using foreach
foreach my $fruit (@fruits) {
print "I like $fruit\n";
}
# Using for loop
for (my $i = 0; $i < @fruits; $i++) {
print "$fruits[$i]\n";
}
# Using index
for my $index (0..$#fruits) {
print "Index $index: $fruits[$index]\n";
}Array to Scalar Conversion
perl
# Array to scalar (get length)
my @array = (1, 2, 3, 4, 5);
my $count = @array; # $count = 5
# Scalar list to array
my ($a, $b, $c) = (1, 2, 3);
# Array expansion
my @array1 = (1, 2, 3);
my @array2 = (4, 5, 6);
my @combined = (@array1, @array2); # (1, 2, 3, 4, 5, 6)
# Array assignment to scalar (returns element count)
my $num = @array1; # $num = 3Hashes
Creating Hashes
perl
# Empty hash
my %empty = ();
# Create from list (key-value pairs)
my %person = (
name => "Alice",
age => 25,
city => "New York"
);
# Using commas
my %scores = (
"math", 90,
"english", 85,
"science", 92
);
# Mixed style
my %data = (
"name" => "Bob",
age => 30,
"city" => "London"
);Accessing Hash Elements
perl
my %person = (name => "Alice", age => 25);
# Access single value (use $ prefix)
print $person{name}; # Output: Alice
print $person{age}; # Output: 25
# Modify value
$person{age} = 26;
# Accessing non-existent key returns undef
print $person{city}; # Output: (empty or warning)Hash Operations
perl
my %person = (name => "Alice", age => 25, city => "New York");
# Get all keys
my @keys = keys %person; # (name, age, city)
my @sorted_keys = sort keys %person; # Sorted keys
# Get all values
my @values = values %person; # (Alice, 25, New York)
# Get key-value pairs
my @pairs = %person; # Expand to list
while (my ($key, $value) = each %person) {
print "$key: $value\n";
}
# Check if key exists
if (exists $person{name}) {
print "Name exists\n";
}
# Delete key-value pair
delete $person{age};
# Hash length
my $count = keys %person; # Returns number of keys
# Clear hash
%person = ();Hash Iteration
perl
my %scores = (math => 90, english => 85, science => 92);
# Iterate over keys
foreach my $subject (keys %scores) {
print "$subject: $scores{$subject}\n";
}
# Iterate over values
foreach my $score (values %scores) {
print "Score: $score\n";
}
# Iterate over key-value pairs
while (my ($subject, $score) = each %scores) {
print "$subject: $score\n";
}Type Conversion
Automatic Conversion
Perl automatically converts between numbers and strings:
perl
# Number to string
my $num = 42;
my $str = "Number: " . $num; # "Number: 42"
# String to number
my $string = "123";
my $value = $string + 10; # 133
# Non-numeric string converts to 0
my $text = "abc";
my $result = $text + 5; # 5Forced Conversion
perl
# Force to number
my $str = "123abc";
my $num = int($str); # 123
my $float = 0 + $str; # 123
# Force to string
my $number = 456;
my $text = "" . $number; # "456"
my $text2 = "$number"; # "456"Special Variables
Default Variable $_
perl
# $_ is default input and pattern search variable
$_ = "Hello World";
print; # Print $_
# Automatically set in loops
foreach (1..5) {
print; # Print $_
}
# grep and map use $_
my @numbers = (1, 2, 3, 4, 5);
my @evens = grep { $_ % 2 == 0 } @numbers; # (2, 4)
my @squared = map { $_ * $_ } @numbers; # (1, 4, 9, 16, 25)Practice Examples
Example 1: Shopping List
perl
#!/usr/bin/perl
use strict;
use warnings;
my @shopping_list = qw(apple banana milk bread);
my %prices = (
apple => 2.5,
banana => 1.8,
milk => 3.2,
bread => 4.0
);
print "=== Shopping List ===\n";
foreach my $item (@shopping_list) {
my $price = $prices{$item} || "N/A";
printf "%-10s: \$%.2f\n", $item, $price;
}Example 2: Student Grade Statistics
perl
#!/usr/bin/perl
use strict;
use warnings;
my %students = (
Alice => { math => 90, english => 85, science => 92 },
Bob => { math => 78, english => 92, science => 88 },
Charlie => { math => 95, english => 89, science => 97 }
);
foreach my $name (keys %students) {
my $scores = $students{$name};
my $sum = $scores->{math} + $scores->{english} + $scores->{science};
my $average = $sum / 3;
printf "%-10s: Math=%d, English=%d, Science=%d, Average=%.1f\n",
$name, $scores->{math}, $scores->{english},
$scores->{science}, $average;
}Summary
In this chapter, we learned Perl's data types:
- ✅ Scalars: Single values (numbers, strings, references)
- ✅ Arrays: Ordered lists of values
- ✅ Hashes: Key-value pairs
- ✅ Type conversion
- ✅ Special variables
Next, we will learn Perl Variables and Perl Operators.