You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[aeiou] # Any vowel
[^aeiou] # Any consonant
[a-z] # Any lowercase letter
[0-9A-F] # Hex digit
Modifiers
/pattern/i# Case insensitive/pattern/g# Global/pattern/m# Multi-line/pattern/s# Single line (dot matches \n)/pattern/x# Extended (allow whitespace and comments)
Examples
# Email validation$email =~ /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i;
# Split with regex@parts = split(/\s+/, $string); # Split on whitespace# Extract all numbers@numbers = $string =~ /\d+/g;
# Substitution with evaluation$string =~ s/(\d+)/$1 * 2/ge; # Double all numbers
11. File I/O
# Opening filesopen(my$fh, '<', 'input.txt') ordie"Cannot open: $!";
open(my$out, '>', 'output.txt') ordie"Cannot open: $!";
open(my$log, '>>', 'debug.log') ordie"Cannot open: $!";
# Readingwhile (my$line = <$fh>) {
chomp$line; # Remove newlineprint$line;
}
# Using $_ (default variable)while (<$fh>) {
chomp;
print$_;
}
# Reading entire filemy@lines = <$fh>;
my$content = do { local$/; <$fh> }; # Slurp mode# Writingprint$out"Hello\n"; # Using filehandlesay$out"Hello"; # With newline (5.10+)# File testsif (-e"file.txt") { print"Exists\n"; }
if (-f"file.txt") { print"Regular file\n"; }
if (-d"dir") { print"Directory\n"; }
if (-r"file.txt") { print"Readable\n"; }
if (-w"file.txt") { print"Writable\n"; }
if (-x"file") { print"Executable\n"; }
if (-z"file.txt") { print"Empty\n"; }
if (-s"file.txt") { print"Size: " . (-s"file.txt") . "\n"; }
if (-T"file.txt") { print"Text file\n"; }
if (-B"file.txt") { print"Binary file\n"; }
# File operationsrename("old.txt", "new.txt") ordie"Rename failed: $!";
unlink("file.txt") ordie"Delete failed: $!";
mkdir("newdir", 0755) ordie"Mkdir failed: $!";
rmdir("emptydir") ordie"Rmdir failed: $!";
# Filehandles (autoclose at scope end)open(my$fh, '<', 'file.txt') ordie"Cannot open: $!";
# ... use $fh ...# File automatically closes when $fh goes out of scope# STDIN/STDOUT/STDERR$line = <STDIN>;
printSTDOUT"Output\n";
printSTDERR"Error message\n";
# Using File::Slurp (CPAN)use File::Slurp qw(read_file write_file);
my$text = read_file('file.txt');
write_file('output.txt', $text);
# Defining a packagepackageMyModule;
use strict;
use warnings;
our$VERSION = "1.0";
subnew {
my$class = shift;
my$self = { @_ };
returnbless$self, $class;
}
submethod {
my$self = shift;
return$self->{data};
}
1; # Must return true# Using modulesuse MyModule; # Load at compile timerequire MyModule; # Load at runtimeuse MyModule qw(function1 function2); # Import specific functionsuse MyModule (); # Load but don't import# Object-oriented usagemy$obj = MyModule->new(data=>"value");
print$obj->method();
# Exporter (for function export)packageMyUtils;
use parent 'Exporter';
our@EXPORT = qw(util1 util2); # Auto-exportour@EXPORT_OK = qw(util3 util4); # Optional exportour%EXPORT_TAGS = (all=> [@EXPORT, @EXPORT_OK]);
subutil1 { ... }
subutil2 { ... }
1;
# Using Exporteruse MyUtils; # Gets util1, util2use MyUtils qw(util3); # Gets only util3use MyUtils qw(:all); # Gets everything# Namespace manipulationpackagemain; # Back to main namespace$MyModule::variable = 42; # Package variable access# Perl modules naming convention# Core: File::Basename, Getopt::Long# CPAN: JSON, DBI, Moose# Local: lib/My/Module.pm = My::Module# Best practicesuse strict;
use warnings;
use v5.36; # or higher
14. Error Handling
# die - terminate with errordie"Something went wrong\n";
die"Error: $!"; # Include system error# warn - print warning (non-fatal)warn"Warning: File not found\n";
# eval - trap exceptionseval {
open(my$fh, '<', 'missing.txt') ordie"Cannot open: $!";
# ... more code ...
};
if ($@) { # Error caughtprint"Caught error: $@\n";
}
# $@ contains the error from last eval# autodie (recommended)use autodie;
open(my$fh, '<', 'missing.txt'); # Dies automatically# Try::Tiny (CPAN)use Try::Tiny;
try {
die"error";
} catch {
warn"Caught: $_";
};
# Carp module (better stack traces)use Carp;
carp "Warning (caller's perspective)";
cluck "Full stack trace warning";
croak "Error (reported at caller's line)";
confess "Error with full stack trace";
# Fatal warnings (5.10+)use warnings FATAL=>'all';
# Custom exceptionspackageMyException;
use overload '""'=>sub { shift->{message} };
subthrow {
my ($class, $message) = @_;
diebless { message=>$message }, $class;
}
# Using custom exceptioneval {
MyException->throw("Custom error");
};
if (blessed($@) && $@->isa('MyException')) {
print"Caught custom: $@\n";
}
15. Special Variables
$_# Default variable (most used)@_# Subroutine arguments$!# System error message / errno$@# Error from last eval$$# Process ID$0# Program name
$^O # Operating system name
$^T # Script start time (epoch)$|# Autoflush (1=enabled, 0=disabled)$.# Current line number for last filehandle read$"# List separator (used in interpolation)$,# Output field separator for print$\# Output record separator (added after print)$/# Input record separator (default newline)@ARGV# Command line arguments@INC# List of include directories%ENV# Environment variables%SIG# Signal handlers# Some exampleslocal$| = 1; # Disable bufferinglocal$/ = undef; # Slurp mode (read whole file)local$" = ", "; # @array interpolation: "1, 2, 3"$SIG{INT} = sub { die"Interrupted\n" }; # Ctrl-C handler
16. Built-in Functions
Scalar functions
chomp($var); # Remove trailing newlinelength($str); # String lengthlc($str); # Lowercaseuc($str); # Uppercaselcfirst($str); # First char lowercaseucfirst($str); # First char uppercaseindex($str, $sub); # Find substring positionrindex($str, $sub); # Find last positionsubstr($str, $off, $len); # Extract substringreverse($str); # Reverse stringint($num); # Integer part
abs($num); # Absolute valuerand($max); # Random number [0, max)srand($seed); # Seed random generatordefined($var); # Check if definedundef($var); # Undefine variablehex($str); # Hex to decimaloct($str); # Octal to decimalchr($num); # Number to characterord($char); # Character to number
time(); # Current epoch secondslocaltime(); # Local time (list/string)gmtime(); # GMT timesleep($seconds);
usleep($microseconds);
Other utilities
eval($string); # Run Perl codedo($file); # Execute Perl filesystem(@cmd); # Run shell commandexec(@cmd); # Replace processqx/ls -l/; # Backticks - capture output`ls -l`; # Same as above
17. One-Liners
# Common perl one-liners (run from command line)# Replace text in file (in-place)
perl -pi -e's/old/new/g' file.txt
# Print lines matching pattern
perl -ne'print if /pattern/' file.txt
# Print lines NOT matching pattern
perl -ne'print unless /pattern/' file.txt
# Print line numbers
perl -ne'print "$.: $_"' file.txt
# Print first 10 lines (head)
perl -pe 'exit if $. > 10' file.txt
# Print last 10 lines (tail)
perl -e'@lines=<STDIN>; print @lines[-10..-1]'# CSV manipulation
perl -F, -lane 'print $F[0]' data.csv # Print first column# Calculate sum of numbers
perl -lne '$sum += $_; END { print $sum }' numbers.txt
# Find duplicate lines
perl -ne'print if $seen{$_}++' file.txt
# Extract email addresses
perl -nle 'print $1 while /([\w.-]+@[\w.-]+\.[a-z]{2,})/gi' file.txt
# Web server (simple)
perl -MHTTP::Server::Simple -e'package My; @ISA = qw(HTTP::Server::Simple); sub handle_request { print "HTTP/1.0 200 OK\n\nHello"; } My->new(8080)->run'# Command line switches# -e Execute code# -p Print after processing (creates while + print)# -n Loop but no automatic print# -i In-place edit (backup with .bak)# -l Auto-chomp and add newline# -a Auto-split into @F# -F Field separator (with -a)# -M Load module# -I Add directory to @INC
18. Best Practices
Always use
use strict;
use warnings;
use v5.16; # or later for modern features
Naming conventions
$scalar_var# snake_case for variables@array_of_names%hash_of_stuff$CamelCase# Package names
snake_case # Subroutines$ALL_CAPS# Constants$_# Only as default, avoid in long blocks
Code organization
#!/usr/bin/perluse strict;
use warnings;
use v5.36;
# Pragmas and use statementsuse Carp;
use autodie;
# Constantsuse constant MAX_SIZE=> 1024;
# Subroutine declarations (optional)subprocess_data;
# Main codesubmain {
my@args = @_;
# ... code ...return 0; # Exit code
}
exit(main(@ARGV));
# Subroutine definitionssubprocess_data {
my ($data) = @_;
# ... code ...
}
Performance tips
# Use local references for speedmy$ref = $array[$i];
for (my$i = 0; $i < @array; $i++) {
my$item = $ref->[$i]; # Faster
}
# Pre-extract array sizemy$size = @array;
for (my$i = 0; $i < $size; $i++) { }
# Avoid creating unnecessary temporary arrayswhile (my ($k,$v) = each%hash) { } # Better than keys# Use grep/map instead of explicit loops when possiblemy@positive = grep { $_ > 0 } @numbers;
# Precompile regexesmy$regex = qr/pattern/;
$string =~ $regex;
# Use single quotes when no interpolation neededprint'$var: '; # Faster for literal strings# Open filehandles with localopen(my$fh, '<', $file) ordie;
# Use file test operators efficientlyif (-r$fileand-w$file) { }
Debugging
# Data::Dumperuse Data::Dumper;
print Dumper($complex_structure);
# Carp::Alwaysuse Carp::Always; # Adds stack traces to all warnings/dies# Debug module
perl -d script.pl
# Smart::Comments (CPAN)use Smart::Comments;
### $var # Shows value when script runs# Use say instead of print (when possible)use v5.10;
say$var; # Adds newline# Profiling
perl -d:DProf script.pl
dprofpp # Analyze output# Perl::Critic (code quality)
perlcritic --brutal script.pl
Common pitfalls
# Don't: Using $a/$b for non-sort (they're special)$c = $a + $b; # OK# Do: use other names# Don't: Forgetting to chomp$input = <STDIN>; # Has newlinechomp($input); # Remove newline# Don't: Using == for stringsif ($str == "hello") # Wrong: numeric comparison# Don't: Overwriting $_ in nested loopsforeach (@outer) {
foreach (@inner) { # $_ overwrittenprint$_;
}
}
# Use named variables instead# Don't: Relying on boolean conversionif ($value) { } # Does NOT work: undef, 0, "0", "" are false# Do: Explicit checksif (defined$value) { }
if ($valueeq"0") { }