Introduction to Perl programming
Perl is a high-level, general-purpose programming language that excels in text processing, system administration, web development, and more. Its flexibility and strong regular expression capabilities make it a popular choice for scripting tasks. This article introduces the basics of Perl programming, including an example script.
Basics of Perl
Running a Perl Script
To execute a Perl script, save the code in a file with a .pl
extension (e.g., script.pl
) and run it from the command line:
perl script.pl
Syntax Highlights
- Shebang Line: Specify the interpreter.
#!/usr/bin/perl
- Comments: Use
#
for single-line comments.# This is a comment
- Printing Output:
print "Hello, World!\n";
Variables
Perl has three main variable types:
- Scalars: Single values (numbers, strings, etc.), prefixed by
$
.my $name = "Eva"; my $age = 35;
- Arrays: Ordered lists, prefixed by
@
.my @colors = ("red", "green", "blue");
- Hashes: Key-value pairs, prefixed by
%
.my %capitals = ("France" => "Paris", "Japan" => "Tokyo");
Control Structures
- Conditional Statements:
if ($age > 18) { print "You are an adult.\n"; } else { print "You are a minor.\n"; }
- Loops:
for my $color (@colors) { print "$color\n"; }
Example Script: Text File Analysis
This script reads a text file, counts the lines, words, and characters, and prints the results.
Script
#!/usr/bin/perl
use strict;
use warnings;
# Check for file argument
if (@ARGV != 1) {
die "Usage: $0 <filename>\n";
}
my $filename = $ARGV[0];
# Open the file
open(my $fh, '<', $filename) or die "Could not open file '$filename': $!\n";
# Initialize counters
my ($line_count, $word_count, $char_count) = (0, 0, 0);
# Process the file
while (my $line = <$fh>) {
$line_count++;
$char_count += length($line);
$word_count += scalar(split(/\s+/, $line));
}
close($fh);
# Print results
print "File: $filename\n";
print "Lines: $line_count\n";
print "Words: $word_count\n";
print "Characters: $char_count\n";
Explanation
- Input Validation: Ensures the script is called with a filename.
- File Handling: Uses
open
andclose
for file operations. - Counters: Tracks lines, words, and characters.
- Loop: Reads the file line by line, processing each line.
Running the Script
Save the script as file_analysis.pl
and run it with a text file:
perl file_analysis.pl sample.txt
Conclusion
Perl is a powerful tool for scripting and data processing. Its concise syntax and robust text-handling capabilities make it an excellent choice for many tasks. This example demonstrates basic Perl features and encourages further exploration of its vast capabilities.