Perl

From Dreamwidth Notes
Jump to: navigation, search

Beginning programming in Perl

Perl Documentation

  • Manual Pages
  • Module documentation
  • FAQ
  • Too, a linux or Mac OS X machine with Perl installed will almost always have the perldoc tool installed...so if you like, you can also access all of the above information from the command line:
    • perldoc perl will give you a list of all the main perldoc pages
    • perldoc Module::Name gives you documentation for that module
    • perldoc -f function shows the documentation for that function
    • perldoc -q search-term searches the Perl FAQ for the term given
    • and of course perldoc perldoc tells you more about how to use perldoc =)

Commonly referenced perldoc pages

Regular Expressions

Perl programmers tend to make extensive use of regular expressions, but they are also used in many other tools (eg vim, less, grep).

Perl Tips

Strings

Interpolating variables inside text

Most of the time, you can simply place a variable inside a double-quoted string, and Perl will expand it for you in the way you want:

my $foo = "Kim";
print "Hi, $foo!";     # prints «Hi, Kim!»

But if the variable name is ambiguous, you can use {} characters to set it apart like so:

$string = "${foo}worthy"

And this way it won't get confused with another variable like $foow, or $fooworth, or what have you.

Clarifying complicated string constructions using printf() or sprintf()

When you're trying to build up a complex string by assembling many different variables and bits of text, things can quickly get unreadable:

my $msg = "At " . DateTime->now() . ", " . $user->name . " did $action" . 
    ", which made " . $action->object . " become " . $action->result . ".";

The Perl function sprintf() lets you build up strings using a kind of mini-templating language. You specify the literal text you want first, with markers that indicate where you want to insert a variable. For instance, %s means "insert a string here". Then list the variables you want inserted.

So, the above example could be reformatted like this:

my $msg = sprintf("At %s, %s did %s, which made %s become %s.", 
    DateTime->now(), $user->name, $action, $action->object, $action->result);

printf() works the same as sprintf(), except it immediately prints the string you built -- so, printf(blah) is pretty much the same as print sprintf(blah).