Why you shouldn't write short code examples in Perl

  • Using $a and $b outside of sort() can have serious consequences.

  • You can't name a subroutine m, q, s, y (at least my favorites f and g aren't taken).

  • Removing duplicate elements from a list:

    PHP:

    php> $ary = array_unique($ary);

    Perl:

    $ sudo su
    # apt-get install curl
    # curl -L http://cpanmin.us | perl - --self-upgrade
    # cpanm List::MoreUtils
    perl> use List::MoreUtils qw(:all);
    perl> @ary = uniq @ary;

Anybody care to add?

6 Comments

@ary = do { my %s; grep { not $s{$_}++ } @ary };

You can name subroutines s, y, m and q, you just have to either call them as methods or with a package qualifier.

Another one-line hack for uniq:

    @uniq = keys %{ { map { $_ => 1 } @array} };

Or you could use Perl 6 for short code examples, where $a and $b are not magical.* In fact, the language generally isn't magical unless you're explicitly using magic syntax like ~~ (smartmatch) or * (whatever).

And you could use whichever of the following three unique filtering examples that you find clearest.

@ary = uniq @ary;

@ary = @ary.uniq;

@ary.=uniq;

I'm not sure off-hand about the ability to define subroutines named m, s, q, or y.

Although Perl 6 is, in my opinion, usually clearer than Perl 5 as pseudocode for examples, remember that pseudocode doesn't actually need to be a real language!

* sort uses standard subroutines with either two-argument signatures[1] or two placeholder variables[2] which start with the $ sigil followed by the ^ twigil, such as $^a and $^b or whatever you want to name them.

1. sort -> $a, $b { $a cmp $b }, @ary

2. sort { $^a cmp $^b }, @ary

Fetching data via HTTP:

use HTTP::Tiny;
my $response = HTTP::Tiny->new->get("http://www.example.com/");
print $response->{content} if $response->{success};

Versus PHP:

<?php
$ch = curl_init("http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  # magic!!
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if (!curl_errno($ch)) print $response;

I know which one I prefer.

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.