Perl Basic Syntax
Hello World Program
Let's start with the classic Hello World program:
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:
Perl Program Structure
Basic Structure
A complete Perl program consists of the following parts:
Comments
Perl uses the # symbol for comments:
Perl Statements
Statement Separator
Perl uses semicolon ; as a statement separator:
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 {}:
Output Statements
print Function
say Function (Perl 5.10+)
The say function automatically adds a newline at the end:
printf Function
Formatted output:
Input Statements
Reading from Standard Input
Simplified Writing
Reading One Line
Variable Declarations
Using strict and warnings
my Declares Local Variables
our Declares Global Variables
local Temporarily Modifies Variables
Code Style Recommendations
Indentation
Use 4 spaces or 1 tab for indentation:
Variable Naming
Parentheses Usage
Compilation and Execution
Direct Execution
Execute as Script
Check Syntax (No Execution)
Enable Warnings
Debug Mode
Practice Examples
Example 1: Simple Calculator
Example 2: User Information Collection
Example 3: Multi-line Input Processing
Common Errors
1. Forgetting Semicolon
2. Undeclared Variables
3. Confusing Scalars and Arrays
4. Typos
Summary
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.