Perl Cheatsheet
Scalars and Operators
Use this Perl reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Scalar Assignment
my $name = "Ada"; my $count = 42; my $pi = 3.14159; my $missing = undef; defined $missing; # false
String Quoting
my $lit = 'literal $name'; # no interpolation except backslash and quote rules my $str = "Hello, $name\n"; # variables and escapes interpolate my $sq = q{single quote style}; my $dq = qq{double quote style $name};
Never declare my $a or my $b: they shadow the package globals sort uses, so a sort { $a <=> $b } in the same scope silently breaks.
Heredocs
my $email = <<~EOT; # ~ strips leading indentation (Perl 5.26+) Dear $name, Your total is $count. EOT my $raw = <<~'EOT'; # single-quoted terminator: no interpolation literal $name stays as-is EOT
Numeric Operators
$x + $y # add $x - $y # subtract $x * $y # multiply $x / $y # divide $x % $y # remainder $x ** $y # exponent ++$x; $x--; # increment/decrement
String Operators
$s . $t # concatenate $s x 3 # repeat string 3 times length $s # character count substr($s, 0, 3) # substring index($s, "needle") # first index or -1 lc $s; uc $s; # lower/upper case
sprintf Recipes
sprintf "%05d", 42; # 00042 (zero-pad to width 5) sprintf "%8.2f", 3.14159; # ' 3.14' (width 8, 2 decimals) sprintf "%-10s|", "left"; # 'left |' (left-justify) sprintf "%x %o %b", 255, 8, 5; # ff 10 101 (hex, octal, binary) sprintf "%e", 12345.678; # 1.234568e+04 sprintf "%s%%", 99; # 99% (literal percent sign)
Numeric vs String Comparison
| Numeric | String | Meaning |
|---|---|---|
== | eq | equal |
!= | ne | not equal |
< | lt | less than |
> | gt | greater than |
<= | le | less or equal |
>= | ge | greater or equal |
<=> | cmp | three-way compare |
if ($n == 10) { ... } # numbers if ($name eq "Ada") { ... } # strings
Defined-Or and Defaults
my $name = shift @ARGV // "world"; # fallback only if undef my $port = $ENV{PORT} || 3000; # fallback for any false value $hash{count} //= 0; # assign default if undef