Perl is a high-level, general-purpose, and interpreted programming language known for its powerful text-processing capabilities. It is widely used for system administration, web development, and network programming.
- Dynamic Typing: No need to declare variable types explicitly.
- Rich Text Processing: Built-in support for regular expressions.
- Cross-Platform: Runs on various operating systems.
- CPAN: Comprehensive Perl Archive Network offers thousands of reusable modules.
- Scripting and Automation: Ideal for automating tasks and quick prototyping.
- Scalar: Stores a single value (string, number, or reference).
my $name = "Perl";
- Array: Ordered list of values.
my @colors = ("red", "green", "blue");
- Hash: Key-value pairs.
my %ages = ("Alice" => 30, "Bob" => 25);
- Perl evaluates expressions in scalar or list context:
my $count = @colors; # Scalar context: Number of elements my @list = @colors; # List context: All elements
- Arithmetic:
+
,-
,*
,/
,%
,**
- String:
.
(concatenation),x
(repetition) - Comparison:
- Numbers:
==
,!=
,<
,>
,<=
,>=
- Strings:
eq
,ne
,lt
,gt
,le
,ge
- Numbers:
- Regular Expressions:
- Match:
=~ /pattern/
- Negated Match:
!~ /pattern/
- Match:
if ($age > 18) {
print "Adult\n";
} elsif ($age > 12) {
print "Teenager\n";
} else {
print "Child\n";
}
- For Loop:
for my $color (@colors) { print "$color\n"; }
- While Loop:
while ($age < 30) { $age++; }
- Define reusable code blocks:
sub greet { my $name = shift; return "Hello, $name!"; } print greet("Alice");
- Perl excels at text manipulation:
my $string = "Hello World"; if ($string =~ /World/) { print "Match found!\n"; } $string =~ s/World/Perl/; # Substitution
- Reading 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, ">", "file.txt") or die "Cannot write to file: $!"; print $fh "Hello, Perl!\n"; close($fh);
- Import modules using
use
:use strict; use warnings; use Math::Complex;
- Create reusable modules:
package MyModule; sub hello { return "Hello, Perl!"; } 1;
- Run scripts with debugging enabled:
perl -d script.pl
- Use
warn
anddie
for error messages:warn "This is a warning\n"; die "This is a fatal error\n";
- Use
use strict;
anduse warnings;
to catch errors. - Use meaningful variable names and proper indentation.
- Leverage CPAN modules for reusable functionality.
- Perl Official Documentation: https://perldoc.perl.org/
- CPAN: https://www.cpan.org/
- Learning Perl: Popular book for beginners, also known as the "Llama book."
Perl is a versatile and robust language with extensive support for text processing and automation tasks, making it a valuable tool for developers and system administrators.