Perl One-Liners

Posted by Vijayant Kumar

What are Perl One-Liners?

As the name suggests, Perl One-Liners are small single line of codes that can perform several tasks, ranging from changing line spacing and numbering lines to converting and substituting text, and from doing calculations to editing files. The Perl One-Liners can run on UNIX Shell or on command-line of any OS where Perl is installed.

Important Syntax’s

The “-e” (execute) flag is what allows us to specify the Perl code we want to run right on the command line.

The “-p” flag (printing loop) processes the file line by line and prints the output.

The “-i” flag is used to directly modify the content in the file. Before you do that, test your one-liner without the -i to ensure it is what you want.

“-0777” changes the line separator to undef, allowing us to slurp the file and feeding all the lines instantly to Perl.

Example Programs

We share some simple examples, to help you better understand Perl One-Liners.

1. Replace a string in multiple files at once

perl -p -i.bak -e ‘s/java/perl/g’ file1 file2 file3

This code replaces all occurrences of “java” in the files by “perl”. To avoid any mistake, we also create a backup file using ‘-i.bak”.

2. Generate a random 8 character password

perl -le ‘print map { (“a”.. “z”)[rand 26] } 1..8’

This one-liner generates and prints a random 8 character password. It uses the list range operator (..)  to produce all strings from “a” to “z”. The map function executes (“a”..”z”)[rand 26] code 8 times because it iterates over the dummy range 1..8. In each iteration the code chooses a random letter from the alphabet by “rand 26”. After the iteration is completed, the map function returns the generated list of characters and the print function prints it by concatenating all the characters together.

3. To find all repeated lines in a file

perl -ne ‘print if $a{$_}++’ file

The code records all the lines seen so far in the %a hash and also keeps a count of the occurrence of the same line in the file. The “$a{$_}++” creates elements in the %a hash . Whenever it sees a repeated line, the value of that hash element is defined. If $a{$_} is true and greater than zero it prints the line. The “-n” command line argument loops over the input but unlike “-p” command it doesn’t prints the lines automatically, which is why we need to use print explicitly.

4. One-liner that numbers repeated lines

perl -ne ‘print “$. $_” if $a{$_}++’

Through this one-liner each line is replaced by the string “$. $_”, which happens to be the current line number followed by the line itself, while “$a{$_}++” creates elements in the %a hash .

5. Find the decimal number that corresponds to an IP

perl -le ‘print unpack(“N”,’

This code uses a “vstring”, a version literal. Here the IP address is a version string, which is nothing but numbers 127, 0, 17, 1 concatenated. The “unpack” function unpacks these numbers to a single decimal number.

6. Numeric values for characters in the string.

perl -le ‘print join “, “, map { ord } split //, “hello”

In this one-liner the string “hello” is split into a list of characters by “split //”. Then it maps the “ord” function onto each character, returning their respective numeric value, a native 8-bit encoding – ASCII or EBCDIC. Finally, all the numeric values are joined together, separated by a comma, and printed.

Another way to do this is use the “unpack” function and specify C* as the unpacking template, where C means unsigned character and * means the number of characters there are.

perl -le ‘print join “, “, unpack(“C*”, “hello”)’

7. Find palindromes in a dictionary

perl -lne ‘print if $_ eq reverse’ /usr/share/dict/words

8. List of the names of all users on the system

perl -a -F: -lne ‘print $F[4]’ /etc/passwd

The combination of “-a” and “-F” argument allows specification of the character where lines should be split. In this case it is the colon, which is the record separator of /etc/passwd. The code also prints the 5th field “$F[4]”, which happens to be the real name of the user.

9. URL-escape a string

perl -MURI::Escape -lne ‘print uri_escape($string)’

In this one-liner, we use the URI::Escape module from CPAN. It exports the “uri_escape” function that performs the URL-escaping.

Now we shall see a few examples to show the mathematical calculations using perl one liner

10. Calculate the factorial

perl -MMath::BigInt -le ‘print Math::BigInt->new(5)->bfac()’

In this code, we use the “bfac()” function from the Math::BigInt module in the Perl core, thus, we do not have to install this module. The “Math::BigInt->new(5)” construction creates a new Math::BigInt object with a value 5, after which the “bfac()” method calculates the factorial of 5 and prints the output.

11. Calculate the least common multiple

perl -MMath::BigInt=blcm -le ‘print blcm(35,20,8)’

To find the least common multiple (lcm), “blcm” function is included in Math::BigInt.

Math::BigInt also includes several other useful math functions such as “bgcd”, the function to calculate the greatest common divisor (gcd) of a list of numbers.

perl -MMath::BigInt=bgcd -le ‘print bgcd(20,60,30)’

These small examples are good enough to get you started with Perl One-Liners. Run these programs on the UNIX Shell or on command-line of any OS to get more familiar with the coding. Do share your feedback on your experience.

That’s it from our side.

Until next time,


Related Posts

  • Understanding Memory Tuning in JVM- A Case Study and Analysis

    JVM Heap Model The JVM heap model consists of the Young generation and the Old generation memory. The newly created objects are allocated to the young generation memory, as they…


    Dancer2 is a more powerful, new generation of Dancer, the lightweight web-framework for Perl. It is a complete rewrite based on Moo and is known as a "micro" web framework,…

  • Hadoop Cluster Verification (HCV)Hadoop Cluster Verification (HCV)

    Verification scripts basically composed of idea to run a smoke test against any Hadoop component using shell script. HCV is a set of artifacts developed to verify successful implementation of…

  • Packaging Web Applications into Dockers, for AWS Containerized DeploymentsPackaging Web Applications into Dockers, for AWS Containerized Deployments

    Overview and Benefits Packing applications into Docker containers allows developer to quickly deploy an application with all its dependencies, which are bundled into a single container and deployed anywhere without…

  • Real time data ingestion – Easy and Simple (co-dev opportunity)Real time data ingestion – Easy and Simple (co-dev opportunity)

    This work is based on Xavient co-dev initiative where your engineers can start working with our team to contribute and build your own platform to ingest any kind of data…

  • Introduction to Messaging

    Messaging is one of the most important aspects of modern programming techniques. Majority of today's systems consist of several modules and external dependencies. If they weren't able to communicate with…

Leave a Reply

Your email address will not be published. Required fields are marked *