Perl

From Code Self Study Wiki
Jump to: navigation, search

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

Quotes[edit]

Double quotes interpolate variables (like in PHP).

You can also use heredocs:

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

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

Data Types[edit]

  • 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'}";

Ranges[edit]

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

Perl REPL[edit]

perl -de1

Command Line Options[edit]

  • 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 "http://www.example.com"'
  • 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[edit]

Remove Lines from Files[edit]

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[edit]