1. Basic Syntax
- Hello World:
print "Hello, World!\n";
- Comments:
# This is a single-line comment
2. Variables
- Scalar Variables:
$
for single values
my $name = "Alice"; my $age = 30;
- Array Variables:
@
for lists
my @fruits = ("apple", "banana", "cherry");
- Hash Variables:
%
for key-value pairs
my %colors = ("red" => "#FF0000", "green" => "#00FF00");
3. Control Structures
-
- If Statement:
if ($age > 18) { print "Adult\n"; } elsif ($age == 18) { print "Just turned adult\n"; } else { print "Minor\n"; }
- Switch Statement (given as
given/when
):
given ($color) { when ("red") { print "Color is red\n"; } when ("blue") { print "Color is blue\n"; } default { print "Unknown color\n"; } }
Loops:
- For Loop:
for (my $i = 0; $i < 5; $i++) { print "$i\n"; }
- Foreach Loop:
foreach my $fruit (@fruits) { print "$fruit\n"; }
- While Loop:
my $count = 0; while ($count < 5) { print "$count\n"; $count++; }
- If Statement:
4. Subroutines
- Defining and Calling Subroutines:
sub greet { my ($name) = @_; print "Hello, $name!\n"; }greet("Alice");
5. File I/O
- Reading from a File:
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!"; while (my $line = <$fh>) { print $line; } close($fh);
- Writing to a File:
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!"; print $fh "Hello, File!\n"; close($fh);
6. Regular Expressions
- Matching:
if ($string =~ /pattern/) { print "Match found!\n"; }
- Substituting:
$string =~ s/old/new/g; # Replace all occurrences
7. Error Handling
- Using
eval
:
eval { # Code that may fail }; if ($@) { print "Error: $@\n"; }
8. Modules and Packages
- Using Modules:
use strict; use warnings; use Some::Module;Some::Module::function();
- Creating a Module:
package MyModule; sub hello { return "Hello from MyModule!"; } 1; # End of module
9. Common Built-in Functions
- Length of a String:
my $length = length($string);
- Array Size:
my $size = @array; # Number of elements in the array
- Sorting an Array:
my @sorted = sort @array;
10. Useful Commands
- Run a Perl Script:
perl script.pl
- Check Syntax:
perl -c script.pl
- Install CPAN Modules:
cpan Module::Name
11. Useful Resources
- Official Documentation: Perl Documentation
- Perl Monks: Community support and discussion.
- CPAN: Comprehensive Perl Archive Network for modules.