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?
@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} };Neil, your snippet doesn't preserve the original order of the array.
Most of the time, I'd install List::MoreUtils rather than having to type that all the time, or moreover explain that to beginners!
Or you could use Perl 6 for short code examples, where
$aand$bare 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, ory.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!
*
sortuses standard subroutines with either two-argument signatures[1] or two placeholder variables[2] which start with the$sigil followed by the^twigil, such as$^aand$^bor whatever you want to name them.1.
sort -> $a, $b { $a cmp $b }, @ary2.
sort { $^a cmp $^b }, @aryFetching 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.