From Code Self Study Wiki
Jump to: navigation, search

This is the Perl 5 page. See also Perl 6.


Double quotes interpolate variables (like in PHP).

You can also use heredocs:

var $some_variable = <<"EOF";
Lorem ipsum
this is some text
another line

That one interpolates variables, because the EOF is in double quotes.

Data Types

  • Scalars -- single units, preceded with $
  • Arrays -- preceded with @. Example: @monsters = ("Beholder", "Titan", "Kobold"); print $monsters[0]; You can alternately use @arr = qw/each of these words becomes an array element/
  • Hashes -- preceded with %

Hash example:

%beholder = ('name', 'Bob', 'eyes', 500, 'hit points', 200);
print "The beholder's name is $beholder{'name'}";


@r = (0..99);
print @r[20];
# Get the size of the array
print scalar @r;


perl -de1

Command Line Options

  • perl -T -- taint mode.
  • perl -t -- taint mode warnings
  • perl -c file.{pl,pm} -- checks for syntax errors
  • perl -w -- finds useful warnings in the code
  • perl -W -- finds all warnings
  • perl -e 'code' -- runs some code, like perl -e 'print "Saluton, Mondo!\n"'
  • perl -n -- runs on every line of standard input. $_ will contain the lines. Example: perl -n -e 'print "Line #$. - $_"' file
  • perl -p -- same as -n but prints the contents of $_
  • perl -i -- modifies the file in place, saving the changes. You can save the original in a backup file like so: perl -i.bak -pe 's\bPHP\b/Python/g' file.txt
  • perl -M -- uses a module, e.g., perl -MLWP::Simple -e'print head ""'
  • perl -l -- without arguments, adds newline to every line
  • perl -d -- runs the Perl debugger
  • I/O -- perl -pe 'some code' < input.txt > output.txt

To research:

  • TODO: -pi, -e, -ne, -pe, -lane, -le -a -F: -lne

Perl One-Liners

Remove Lines from Files

The following example removes all blank lines from a file. You can change the regular expression to change the behavior. The -i.bak edits the file in place and creates a backup file before making the changes.

perl -i.bak -ne 'print if /\S/' filename.txt

Perl Tutorials