Perl by Example: Modules
Organizing and reusing code with this sample code demonstrating module loading with use statement, core module functionality, CPAN ecosystem access, namespace management with packages, and Data::Dumper for structure visualization.
Code
#!/usr/bin/perl
use strict;
use warnings;
# Use a core module
use File::Basename;
use Data::Dumper;
my $path = "/usr/local/bin/perl";
my $filename = basename($path);
my $dir = dirname($path);
print "File: $filename, Dir: $dir\n";
# Data::Dumper is great for debugging complex structures
my %config = (
root => "/var/www",
port => 8080,
users => ["admin", "guest"]
);
print Dumper(\%config);Explanation
Perl modules are discrete components of software stored in .pm files that provide code organization, reusability, and encapsulation of functionality. Modules typically contain subroutines and variables within their own namespace (package) and can be incorporated into scripts using the use statement which loads modules at compile time, or require which loads at runtime. The use statement also allows importing specific functions into the current namespace.
Core modules are included with Perl installations and provide essential functionality without requiring external installation. Examples include File::Basename for portable path manipulation, Data::Dumper for data structure visualization, Carp for enhanced error reporting, and Getopt::Long for command-line argument parsing. These modules ensure cross-platform compatibility and provide tested, optimized implementations of common tasks.
CPAN (Comprehensive Perl Archive Network) is a vast online repository containing over 220,000 open-source Perl modules and documentation. The cpan command-line tool, or modern alternatives like cpanm (cpanminus) or cpanplus, acts as an interface to this network allowing users to search, download, and install modules automatically with dependency resolution. CPAN provides modules for web development, database integration, text processing, networking, and virtually any programming task.
Code Breakdown
use File::Basename loads core module at compile time.basename() and dirname() provide portable path parsing.Dumper(\%config) takes reference, recursively prints structure for debugging.Data::Dumper converts complex data structures to readable string representation.
