From Novice to Adept: Pronouns in Perl

One of the persistent criticisms of Perl is that it has too many implicit variables. These are variables on which certain built in operations work if you don't provide explicit targets.

The funny thing about that criticism is that anyone who can read and understand the previous two sentences appropriately can understand Perl 5's two pronouns.

It in Perl 5

The first -- and most used -- pronoun in Perl 5 is $_. This is the default variable. You may also hear it called the topic variable. A few operations set it. Several operations operate on it. Whenever you see $_, read it as "it".

For example, when you iterate over a list without an explicit iterator, Perl internally aliases $_ to the current iteration value:

for (1 .. 10)
{
    say;
}

This example shows off the implicit use of $_ as well; say with no arguments operates on the current value of $_. You can write this explicitly if you want (say $_;), but idiomatic Perl eschews the use of the topic unless necessary.

An interesting technique is deliberate assignment to $_ to enable implicit reference:

for ($some_var)
{
    /foo/ and do { ... };
    /bar/ and do { ... };
    /baz/ and do { ... };
}

Perl 5.10's given/when construct cleaned that up:

use Modern::Perl;

given ($some_var)
{
    when (/foo/) { ... }
    when (/bar/) { ... }
    when (/baz/) { ... }
}

A little bit of extra syntax in the form of new keywords clarifies the intent of the code.

These in Perl 5

The other pronoun in Perl 5 is @_, for these or them. Most of the uses of this pronoun in modern Perl is in handling function parameters. You can get at the invocant of a method with:

sub my_method
{
    my $self = shift;
    ...
}

... though it's often more succinct to handle multiple parameters with list assignment:

sub my_other_method
{
    my ($self, $name, @args) = @_;
    ...
}

Unlike $_, few built in operators operate on or set @_ implicitly. You can refer to it implicitly if you use the goto idiom for tail call elimination or if you use Perl 4-style function calls... but don't do either one.

Modern Perl: The Book

cover image for Modern Perl: the book

The best Perl Programmers read Modern Perl: The Book.

affiliated with ModernPerl.net

Categories

Pages

About this Entry

This page contains a single entry by chromatic published on November 9, 2009 3:22 PM.

A Language's Tools (CPAN versus IDEs) was the previous entry in this blog.

How Perl Happens is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.


Sponsored by Blender Recipe Reviews and the Trendshare how to invest guide

Powered by the Perl programming language

what is programming?