AI Generate Perl docs instantly

Perl Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Basic Perl syntax and first programs

Hello World

print "Hello, World!\n";

Shebang

#!/usr/bin/perl
use strict;
use warnings;

Comments

# Single line comment

=begin
Multi-line comment
=cut

Print vs Say

print "No newline";
say "With newline";  # Requires use 5.010

Execute Perl

perl script.pl
perl -e 'print "code\n"'  # One-liner

Variables & Data Types

7 snippets

Scalars, arrays, hashes, and references

Scalar Variables

my $name = "John";
my $age = 30;
my $price = 19.99;

Arrays

my @fruits = ("apple", "banana", "cherry");
my @numbers = (1, 2, 3, 4, 5);

Hashes

my %person = (
    name => "John",
    age => 30,
    city => "NYC"
);

Array Access

$fruits[0];        # "apple"
$fruits[-1];       # Last element
scalar(@fruits);   # Length

Hash Access

$person{name};     # "John"
keys %person;      # ("name", "age", "city")
values %person;    # Values

References

my $arrayref = \@fruits;
my $hashref = \%person;
$arrayref->[0];    # Access
$hashref->{name};  # Access

Undef

my $value = undef;
if (!defined($value)) { print "undef\n"; }

Operators

6 snippets

Arithmetic, comparison, and logical operations

Arithmetic

$a + $b;  # Addition
$a - $b;  # Subtraction
$a * $b;  # Multiplication
$a / $b;  # Division
$a % $b;  # Modulus
$a ** $b; # Exponent

String Operations

$str . $str2;  # Concatenation
$str x 3;      # Repeat 3 times
$str eq $str2; # String equal
$str ne $str2; # String not equal

Numeric Comparison

$a == $b;  # Equal
$a != $b;  # Not equal
$a > $b;   # Greater
$a < $b;   # Less
$a >= $b;  # Greater or equal
$a <= $b;  # Less or equal

String Comparison

$a eq $b;  # Equal
$a ne $b;  # Not equal
$a gt $b;  # Greater
$a lt $b;  # Less
$a ge $b;  # Greater or equal
$a le $b;  # Less or equal

Logical Operators

$a && $b;  # AND
$a || $b;  # OR
!$a;       # NOT
$a and $b; # Low precedence AND
$a or $b;  # Low precedence OR

Range Operator

1..10;        # (1,2,3,4,5,6,7,8,9,10)
'a'..'e';     # ('a','b','c','d','e')

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Conditionals

4 snippets

Making decisions with if, unless, and ternary

If/Elsif/Else

if ($age > 18) {
    print "Adult";
} elsif ($age > 12) {
    print "Teen";
} else {
    print "Child";
}

Unless

unless ($logged_in) {
    print "Please login";
}

Ternary Operator

my $status = $age >= 18 ? "Adult" : "Minor";

Postfix If

print "Yes" if $condition;
die "Error" unless $ok;

Loops

6 snippets

Iterating with for, foreach, while, and until

For Loop

for (my $i = 0; $i < 10; $i++) {
    print "$i\n";
}

Foreach Loop

foreach my $fruit (@fruits) {
    print "$fruit\n";
}

While Loop

while ($count < 10) {
    $count++;
}

Until Loop

until ($done) {
    # code
}

Loop Controls

last;     # Break
next;     # Continue
redo;     # Restart iteration

Postfix Loops

print "$_\n" for @array;
print "$_\n" while <STDIN>;

Subroutines

5 snippets

Defining and calling subroutines

Define Subroutine

sub greet {
    my ($name) = @_;
    return "Hello, $name!";
}

Call Subroutine

my $msg = greet("John");
greet("John");  # Without parens

Multiple Parameters

sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

Default Parameters

sub greet {
    my $name = shift // "Guest";
    return "Hello, $name!";
}

Reference Parameters

sub modify {
    my $arrayref = shift;
    push @$arrayref, "new";
}

Regular Expressions

5 snippets

Pattern matching and text manipulation

Match

if ($str =~ /pattern/) {
    print "Found!";
}

Substitution

$str =~ s/old/new/;    # First match
$str =~ s/old/new/g;   # Global (all)

Capture Groups

if ($str =~ /(\d+)-(\d+)/) {
    print "First: $1, Second: $2";
}

Modifiers

/pattern/i;  # Case insensitive
/pattern/g;  # Global
/pattern/m;  # Multi-line
/pattern/s;  # Single-line (. matches \n)

Split

my @parts = split(/,/, $str);
my @words = split(/\s+/, $text);

File I/O

5 snippets

Reading and writing files

Open File for Reading

open(my $fh, '<', 'file.txt') or die "Cannot open: $!";
while (my $line = <$fh>) {
    print $line;
}
close($fh);

Open File for Writing

open(my $fh, '>', 'output.txt') or die $!;
print $fh "Hello\n";
close($fh);

Append to File

open(my $fh, '>>', 'file.txt') or die $!;
print $fh "Appended\n";
close($fh);

Read Entire File

open(my $fh, '<', 'file.txt') or die $!;
my $content = do { local $/; <$fh> };
close($fh);

Check File Exists

if (-e 'file.txt') { print "Exists"; }
if (-f 'file.txt') { print "Is file"; }
if (-d 'dir') { print "Is directory"; }

More Cheat Sheets

FAQ

Frequently asked questions

What is a Perl cheat sheet?

A Perl cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Perl. It helps developers quickly look up syntax without searching through documentation.

How do I learn Perl quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Perl concepts?

Key Perl concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Perl code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Perl code using AI.

Code Conversion Tools

Convert Perl to Other Languages

Easily translate your Perl code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Perl Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week