Tuesday, September 6, 2011

Secret Perl Operators: A Quick Reference Guide

Secret Perl Operators: A Quick Reference Guide

The Spaceship Operator <=>

Most commonly used to sort a list of numbers. It compares two values and returns:

  • -1 if $a < $b

  • 0 if $a == $b

  • 1 if $a > $b

  • undef if $a and $b are NaN

my @numbers = (-59, 99, 87, 1900, 42, 1, -999, 30000, 0);
my @sorted = sort { $a <=> $b } @numbers;
# output: -999 -59 0 1 42 87 99 1900 30000



The Eskimo Greeting Operator }{

Frequently found in Perl one-liners, this operator is used alongside the -n command-line option (which wraps the code in a while loop). It effectively closes the loop early, allowing code placed after the operator to execute only once the loop has finished processing all input.

# Emulates `wc -l` to print the total number of lines in a file
perl -lne '}{ print $.' file


The Goatse Operator =()=

Forces an expression on the right to be evaluated in a list context. When assigned to a scalar variable, it returns the total number of elements matched on the right-hand side.

my $str = "5 foo 6 bar 7 baz";
my $count =()= $str =~ /\d/g; 
print $count; # Prints 3 (the number of digits found)


The Turtle Operator "@{[]}"

Used for cleanly interpolating an array or a function's returned list directly inside a string.

# Clean interpolation
print "these people @{[get_names()]} get promoted"

# Equivalent to the messier:
print "these people ", join(" ", get_names()), " get promoted"


The Inchworm Operator ~~

Forces a scalar context on an expression that would otherwise be evaluated in a list context.

# Without ~~ (list context forced by print): prints 9 separate date elements
perl -le 'print localtime' 

# With ~~ (scalar context forced): prints human-readable date
perl -le 'print ~~localtime' 
# Mon Nov 30 09:06:13 2009


The Inchworm-On-A-Stick Operator ~-

Effectively decrements numbers greater than zero by one. It parses as (~(-$x)), which acts as $x-1 on a two-complement machine.

my $x = 5;
print ~-$x; # prints 4


The Spacestation Operator -+-

Turns a string that starts with a positive number into an actual number (numification).

print -+-"4zy"   # prints 4
print -+-'3.99'  # prints 3.99
print -+-'2e5'   # prints 200000


The Venus Operator 0+

Performs the same string-to-number numification as the spacestation operator, but binds less tightly

print 0+"4zy"  # prints 4

No comments: