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:
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
$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
, 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!
*
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:
Versus PHP:
I know which one I prefer.