Cool/useful short examples of Perl?

Damian Conway damian at conway.org
Tue May 31 01:45:44 BST 2011


Uri wrote:

> ever taken a class with damian? he doesn't pussy foot around with
> kiddie code. that line is just like stuff he trains with

No it isn't. Not in my beginners classes, nor in PBP. When I'm teaching
newcomers to Perl, I focus my examples entirely on readability and
maintainability.

For example--and these may be relevant to Dave's original
request--here's an improved implementation of uniq in Perl
(improved in the sense that it doesn't require the repeated lines to
be adjacent):

    my %have_printed;
    while (my $line = readline) {
        next if $have_printed{$line};
        print $line;
        $have_printed{$line} = 1;
    }

The nice thing about this example, is that you can then show
small improvements very easily. For instance, to ignore repeated
lines case-insensitively:

    my %have_printed;
    while (my $line = readline) {
        next if $have_printed{lc $line};
        print $line;
        $have_printed{lc $line} = 1;
    }

and then you can use the repeated call to lc to motivate the use
of the slightly more idiomatic (and hence slightly less
obvious-to-newcomers):

    my %have_printed;
    while (my $line = readline) {
        next if $have_printed{lc $line}++;
        print $line;
    }

And then you can show one of the handy new features of Perl 5.14,
by extending the example to ignore differences in whitespacing
as well:

    my %have_printed;
    while (my $line = readline) {
        my $abstract_line = lc( $line =~ s/\s+/ /rg );
        next if $have_printed{$abstract_line}++;
        print $line;
    }

(Note the injection of an interim variable in that last example,
precisely because it improves the comprehensibility of the code.)

>From there you can keep adding to the example in further small steps:
print only lines that *are* repeated, print each line with a repetition
count, specifying which parts of each line to consider/ignore, etc. etc.

I'll happily concede that this example isn't nearly as impressive as
some of the others in this thread, but its real-world, useful,
conveniently incremental, requires no modules, and ably
demonstrates the value of many core features of Perl.

Damian


More information about the london.pm mailing list