Practical Examples and Projects in Perl

April 19, 2024

In this final lesson, we will apply our knowledge of Perl to practical examples and projects. We will explore real-world scenarios and demonstrate how to leverage Perl’s capabilities to solve complex problems, reinforcing our understanding of the language.

Project 1: Text Processing

Let’s start with a practical example of text processing. Suppose we have a text file containing a list of names, and we want to extract only the names that start with the letter ‘A’.

<perl>
open(my $file, '<', 'names.txt') or die 'Could not open file';
while(my $line = <$file&gt) {
    chomp $line;
    if($line =~ /^A/i) {
        print $line . "\n";
    }
}
close($file);
</perl&gt

Project 2: Data Manipulation

For our next project, let's consider a scenario where we have a CSV file with employee data, and we need to calculate the total salary of all employees.

<perl>
use Text::CSV;
my $csv = Text::CSV->new();
open(my $file, '<', 'employees.csv') or die 'Could not open file';
my $total_salary = 0;
while(my $row = $csv->getline($file)) {
    $total_salary += $row->[2];
}
close($file);
print 'Total Salary: ' . $total_salary;
</perl>

Project 3: Web Scraping

Lastly, let's explore web scraping using Perl. We will fetch data from a website and extract specific information.

<perl>
use LWP::Simple;
my $url = 'http://example.com';
my $content = get $url;
if($content) {
    while($content =~ /<title>(.*?)<\/title>/g) {
        print $1 . "\n";
    }
}
</perl>