Perl Basic Syntax
Hello World Program
Let's start with the classic Hello World program:
perl
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";Code explanation:
#!/usr/bin/perl: Called shebang, tells the system which interpreter to use to execute the scriptuse strict;: Enables strict mode, requiring variable declarationsuse warnings;: Enables warnings to help discover potential issuesprint: Output function\n: Newline character
Run the program:
bash
chmod +x hello.pl
./hello.plPerl Program Structure
Basic Structure
A complete Perl program consists of the following parts:
perl
#!/usr/bin/perl # Shebang line (optional but recommended)
# Pragma (compile directives)
use strict;
use warnings;
use v5.38; # Specify Perl version
# Main program code
# ... your code ...
1; # Return true value (required in modules)Comments
Perl uses the # symbol for comments:
perl
# This is a single-line comment
use strict; # End-of-line comments also work
=begin comment
This is a multi-line comment
that can span multiple lines
=end comment
=for comment
This is also another way
to write multi-line comments
=cutPerl Statements
Statement Separator
Perl uses semicolon ; as a statement separator:
perl
print "First statement\n";
print "Second statement\n";Note: The semicolon after the last statement can be omitted, but for clarity, it's recommended to always use a semicolon.
Statement Blocks
Statement blocks are enclosed in curly braces {}:
perl
{
print "Block start\n";
print "Code inside block\n";
print "Block end\n";
}Output Statements
print Function
perl
print "Hello\n"; # Basic output
print "Hello", " ", "World", "\n"; # Multiple arguments
# Without newline
print "Hello "; # Output: Hello World
print "World\n";say Function (Perl 5.10+)
The say function automatically adds a newline at the end:
perl
use v5.10; # or higher version
say "Hello"; # Automatically adds \n
say "World"; # Each output on a new lineprintf Function
Formatted output:
perl
my $name = "Alice";
my $age = 25;
printf "Name: %s, Age: %d\n", $name, $age;
# Output: Name: Alice, Age: 25
# Format numbers
printf "Pi: %.2f\n", 3.14159; # Output: Pi: 3.14
printf "Decimal: %d, Hex: %x, Octal: %o\n", 255, 255, 255;
# Output: Decimal: 255, Hex: ff, Octal: 377Input Statements
Reading from Standard Input
perl
print "Enter your name: ";
my $name = <STDIN>;
chomp $name; # Remove trailing newline
print "Hello, $name!\n";Simplified Writing
perl
print "Enter your name: ";
chomp(my $name = <STDIN>);
print "Hello, $name!\n";Reading One Line
perl
my $line = <STDIN>; # Read one line (including newline)
my $line2 = <>; # Shorthand, equivalent to <STDIN>Variable Declarations
Using strict and warnings
perl
#!/usr/bin/perl
use strict;
use warnings;
# Variables must be declared
my $name = "Alice";
print "$name\n";
# Undeclared variables will cause an error
# print $age; # Error: Global symbol "$age" requires explicit package namemy Declares Local Variables
perl
my $name = "Bob"; # Declare and initialize
my $age; # Declare without initializing (value is undef)
$age = 30; # Assign value
print "$name is $age years old\n";our Declares Global Variables
perl
our $global_var = "global";local Temporarily Modifies Variables
perl
our $var = "original";
{
local $var = "modified"; # Temporarily modify
print "Inside block: $var\n"; # Output: modified
}
print "Outside block: $var\n"; # Output: originalCode Style Recommendations
Indentation
Use 4 spaces or 1 tab for indentation:
perl
if ($condition) {
print "Condition is true\n";
if ($another_condition) {
print "Nested condition\n";
}
}Variable Naming
perl
# Scalars: lowercase letters, words separated by underscores
my $user_name = "Alice";
my $userAge = 25; # CamelCase is also acceptable
# Arrays: plural form or add suffix
my @users = ("Alice", "Bob");
my @user_list = ("Alice", "Bob");
# Hashes: plural form or add suffix
my %user_data = (name => "Alice", age => 25);
my %scores = (math => 90, english => 85);Parentheses Usage
perl
# Function calls can omit parentheses
print "Hello\n";
print("Hello\n"); # Can also use parentheses
# Conditional statements recommend using parentheses
if ($condition) {
# ...
}Compilation and Execution
Direct Execution
bash
perl script.plExecute as Script
bash
chmod +x script.pl
./script.plCheck Syntax (No Execution)
bash
perl -c script.plEnable Warnings
bash
perl -w script.plDebug Mode
bash
perl -d script.plPractice Examples
Example 1: Simple Calculator
perl
#!/usr/bin/perl
use strict;
use warnings;
print "Enter first number: ";
chomp(my $num1 = <STDIN>);
print "Enter second number: ";
chomp(my $num2 = <STDIN>);
print "Choose operation (+, -, *, /): ";
chomp(my $op = <STDIN>);
my $result;
if ($op eq '+') {
$result = $num1 + $num2;
} elsif ($op eq '-') {
$result = $num1 - $num2;
} elsif ($op eq '*') {
$result = $num1 * $num2;
} elsif ($op eq '/') {
$result = $num1 / $num2;
} else {
print "Invalid operator\n";
exit;
}
printf "Result: %.2f\n", $result;Example 2: User Information Collection
perl
#!/usr/bin/perl
use strict;
use warnings;
print "=== User Information Collection ===\n";
print "Name: ";
chomp(my $name = <STDIN>);
print "Age: ";
chomp(my $age = <STDIN>);
print "City: ";
chomp(my $city = <STDIN>);
print "\n=== User Information ===\n";
printf "Name: %s\n", $name;
printf "Age: %d\n", $age;
printf "City: %s\n", $city;
if ($age >= 18) {
print "Status: Adult\n";
} else {
print "Status: Minor\n";
}Example 3: Multi-line Input Processing
perl
#!/usr/bin/perl
use strict;
use warnings;
print "Enter multiple lines (Ctrl+D to end):\n";
my @lines = <STDIN>; # Read all lines into an array
print "\nYou entered " . scalar(@lines) . " lines:\n";
print @lines; # Output all linesCommon Errors
1. Forgetting Semicolon
perl
print "Hello\n" # Error: missing semicolon
print "World\n"; # Syntax error2. Undeclared Variables
perl
use strict;
print $name; # Error: variable must be declared3. Confusing Scalars and Arrays
perl
my @numbers = (1, 2, 3);
print $numbers; # Error: should use @numbers or $numbers[0]4. Typos
perl
my $name = "Alice";
print "$nmae\n"; # Error: variable name typoSummary
In this chapter, we learned Perl's basic syntax:
- ✅ Program structure and comments
- ✅ Input and output statements
- ✅ Variable declarations
- ✅ Code style guidelines
- ✅ Compilation and execution methods
Next, we will learn Perl Data Types.