Chapter 4. Calculations

In this chapter, we’ll look at various one-liners for performing calculations, such as finding minimum and maximum elements, counting, shuffling and permuting words, and calculating dates and numbers. You’ll also learn about the -a, -M, and -F command-line arguments, the $, special variable, and the @{[ ... ]} construction that lets you run code inside double quotes.

4.1 Check if a number is a prime

perl -lne '(1x$_) !~ /^1?$|^(11+?)\1+$/ && print "$_ is prime"'

This one-liner uses an ingenious regular expression by Abigail to detect whether a given number is a prime. (Don’t take this regular expression too seriously; I’ve included it for its artistic value. For serious purposes, use the Math::Primality module from CPAN to ...

Get Perl One-Liners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.