The “perl” Command in Linux [With 4 Practical Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The perl command in Linux is a strong tool for performing a variety of tasks, including text processing and system administration. Perl provides significant support for regular expressions, file manipulation, and automation, allowing users to easily tackle difficult programming challenges from the command line.

In this article, I will demonstrate perl command’s many characteristics using practical examples to show how versatile and efficient it is in a variety of real-world circumstances.

What is “perl” Command in Linux?

In Linux, the perl command is a high-level interpreted programming language that is used for system management and text processing. The acronym perl means “Practical Extraction and Reporting Language”. Larry Wall created it in the late 1980s and published it in 1987. The power of regular expressions in perl made it popular for parsing and processing text files, making reports, and developing web applications.

Linux’s perl command interprets perl scripts. Users can run perl scripts from the command line or shell scripts to automate system administration tasks and other tasks. perl is still used for many programming tasks because of its vast library support and cross-platform interoperability.

Syntax of “perl” Command

The syntax of the perl command typically follows the following format:

perl [options] [programfile] [argument]

Note: The element enclosed by a square bracket in the above syntax is not mandatory.

EXPLANATION
  • perl: Invokes the Perl interpreter.
  • [options]: Represents optional command-line flags that modify perl’s behavior.
  • [programfile]: Specifies the Perl script file to be executed.
  • [argument]: Denotes optional arguments passed to the Perl script during execution.

If you want to know the version history or details info of this command, run the following commands respectively:

perl --version
perl --help

Options of “perl” Command

The perl command has a man page that can help you get all the required information regarding this command. Just write the following command inside your terminal:

man perl

There are several options associated with the perl command. Some of the most used options are:

Option Functionality
-T Enables taint mode in perl and treats all data as untrusted by default, regardless of its source, imposing stricter security measures.
-t Enables tainting warnings. When enabled, perl marks data as “tainted” if it comes from an untrusted source, such as user input or data from the environment.
-u Prompts perl to generate a core dump after compiling your program.
-U Permits perl to perform unsafe operations.
-w Enables all warnings during perl script execution.
-W Enables all warnings regardless of no warnings or $^W.
-X Disables all warnings regardless of use warnings or $^W.
-h Displays a summary of command-line options.
-v Displays the version and patch level of your perl executable.
-V Displays a summary of significant perl configuration values and the current values of the @INC array.
-V[:configvar] Outputs to the standard output the value of the specified configuration variable(s), printing multiple values when the configvar argument resembles a regular expression.
-Dletters-Dnumber Specifies debugging flags to control perl’s execution, with -Dtls used to observe program execution. (Note: Debugging functionality must be compiled into perl for this to work.)
-n Makes perl iterate over file name arguments, akin to the behavior of sed -n or awk loops.
-p Prompts perl to implement a loop around your program, allowing it to iterate over file name arguments similar to the behavior of sed.
-Fpattern Specifies the pattern to split on when -a is active, allowing the use of delimiters like //, “”, or ” with single quotes if whitespace isn’t intended within the pattern.
-0[octal/hexadecimal] Defines the input record separator ($/) as an octal or hexadecimal value. In the absence of digits, the null character serves as a separator. Other switches may occur before or after the digits.
-a When used with -n or -p, it activates auto split mode. An implicit split command to the @F array is executed as the first step within the implicit while loop generated by the -n or -p options.
-d, -dt Runs the program through the perl debugger. If t is given, it informs the debugger that threads are used in the code being debugged.
-e Allows users to input a single line of code directly on the command line. If -e is used, perl doesn’t search for a file name in the arguments. Users can input multiple -e commands to construct a multi-line script, ensuring to include semicolons where appropriate, similar to writing a regular program.
-E Behaves like -e, except that it implicitly enables all optional features
-m[-]module Executes use module(); before executing your program.
-M[-]’module… Executes the ‘use module;‘ statement before running the program, allowing additional code after the module name within quotes.
-f Disables the execution of $Config{sitelib}/sitecustomize.pl at startup.
-C Allows you to specify how perl should handle Unicode in your script. For example, you can enable UTF-8 mode with -CSD, which tells perl to use UTF-8 for both input and output streams.
-s Enables basic parsing of switches placed after the program name but before any file name arguments or the “–” argument delimiter.
-S Makes perl search for the script using the PATH environment variable.
-x-xdirectory Indicates to perl that the program is within a larger, unrelated text like in a mail message, discarding leading garbage until a line starting with #! with perl is encountered.
-i[extension] Edits files in place, optionally creating backup files with the specified extension.
-I(directory) Directories specified by -I are prepended to the search path for modules (@INC ).
-l[octnum] Enables automatic handling of line endings: chomps input record separator when used with -n or -p, and assigns output record separator to a specified octal value.

Practical Examples of Using “perl” Command in Linux

Below, I’ll present a couple of practical applications and examples utilizing the perl command so that you may obtain a deeper grasp of this issue and how to utilize the perl language in Linux more effectively:

1. Options for Scripting Safely & Efficiently

The safety net options in perl provide crucial safeguards for developers, helping to catch errors and prevent security vulnerabilities. There are several safety net options in the perl language.

For example: the -c option compiles the program without executing it, allowing developers to quickly identify syntax errors during editing. Look at the image below:

perl -c command to check syntax error

Other options include -w, which (replaced by use warnings in modern perl) enables warnings that alert developers to potential bugs in their code:

Showing warnings with -w

Lastly, the -T option activates “taint mode,” which treats external data as untrusted, reducing the risk of security breaches. Data in taint mode must be carefully validated before use in certain operations.

2. Executing “perl” Script Written in File

This is the most effective way to run a relatively larger Perl script from the terminal.  Here, you will write your Perl script in a file and then call the file to execute it.

2.1. Basic Script

To run a basic Perl script, first, you need to create a new file, write the script inside it, and save it in a suitable directory. Then, you need to navigate to that directory using the cd command (or, you can just write the full path address from anywhere) and write perl <file name>.
Suppose, you have written the following script inside a file named hello.pl that prints “Hello, World!” to the standard output:

use strict;
use warnings;

print "Hello, World!\n";

Now run the following command:

perl hello.pl

Executing normal script from file

Again, you can run any Perl script without even using the perl command. In that case, you need to add a shebang (#!) line at the beginning of the code and give executable permission to the file using the chmod command.

For example: add this line “#!/usr/bin/perl” at the beginning of the script, save the file, give the executable permission, and run the following command:

./hello.pl

Executing with shebang

Note: The best practice is to always include the shebang (denoted by #!)  line in your script whether you use a specific command or not to execute the script.

2.2. Script With Loops

Loops in programming languages enable the repeated execution of code blocks while iterating over a set of values or items. They are key components for automating processes and effectively processing data across programming paradigms.

The following perl script prints numbers from 1 to 10, each on a new line:

#!/usr/bin/perl

use strict;
use warnings;

# Loop from 1 to 10
for my $i (1..10) {
    print "$i\n";
}

EXPLANATION

This perl script begins by declaring its interpreter location and enabling strict and warnings pragmas for enhanced code quality. It then enters a for loop, iterating from 1 to 10. Within each iteration, it prints the current value of the loop variable $i followed by a newline character. As a result, this script prints numbers from 1 to 10, each on a new line.

Run the following command to execute the script:

perl loop.pl

Executing script containing loop from a file

3. Executing “perl” Single Command Line

You can write your Perl code directly within single quotes after the -e option in the perl command. This method is useful for executing scripts that contain only one line.

3.1. Command-Line Programs

Perl’s command line options provide flexibility in handling input, output, and execution behavior, making it suitable for a wide range of scripting tasks.

For example, run the following command:

perl -e 'print “This is my first perl command line.\n”'

Executing perl in command line

In the above image, you can put any line inside the double quote after the print command.

3.2. Displaying Script Lines from File in Terminal

To display all the consecutive lines of a script written in a file inside the terminal, run the following command:

perl -n -e 'print "$. - $_"' hello.pl

Displaying Script Lines in Terminal

In the above image, all the lines from the file named hello.pl are displayed with numbering.

3.3. Record Separators

Record separators are characters or patterns used to delineate individual records or units of data within a file or stream. To separate the records of a file named fruits.pl with comma (,) run the following command:

perl -F, -pe 's/$/,/' fruits.pl

Separating records by comma

In the above image, the records of the file named fruits.pl have been separated by commas (,). If you want to separate them by other separators, just put that separator in place of the comma between 2 backslashes.

Note: This command does not alter the content of the file. It just shows the record of a file separated by custom separators inside the terminal.

3.4. In-Place Editing

In-place editing in the perl command allows for direct modification of files without the need for creating temporary files or manual intervention. For example, suppose you have a file named orange.pl. Now, you want to replace the word “orange” every time it appears inside the file with “apple” without even accessing the file.

Simply run the following command:

perl -i -pe 's/orange/apple/g' orange.pl

In place editing

In the above image, you can see that the word “apple” replaces the word “orange” inside the file named “orange.pl”. I have used the cat command to view the contents of the file.

4. Executing “perl” scripts Directly From Terminal

There is another way of executing a relatively larger Perl script. Instead of writing a script inside a file and then calling it, you can write your entire script inside the terminal and execute it in the terminal. This method could come in handy if you do not want to create a lot of files that can make you confused.

On the other hand, if you want to store the script you just wrote and want to run the script multiple times, you should always store it inside a file.

To write a script inside the terminal, first, write perl and press ENTER. Then, write the following script as you write it inside a file:

#!/usr/bin/perl

use strict;
use warnings;

# Loop from 1 to 10
for my $i (1..10) {
    print "$i\n";
}

Upon finishing, press CTRL+D to execute the script and show the result:

Executing script directly from terminal using perl command in linux

Conclusion

In this article, I showed you some characteristics of the perl command on Linux, demonstrating its usefulness in automating various processes. I encourage users to explore Perl’s broad capabilities in practical usage.

People May Ask

How do I install perl on Linux?

To install Perl on Linux, you can use the package manager of your distribution. For example, on Debian/Ubuntu, you can use the following command: sudo apt install perl. Perl is often pre-installed on many Linux distributions.

How do I execute a perl script in Linux?

To execute a perl script in Linux, you can use the perl command followed by the name of the perl script file. For example: perl script.pl.

How can I check the syntax of a perl script in the terminal without executing it?

You can use the -c option with the perl command to compile the script without running it. For example: perl -c script.pl.

What are the benefits and limitations of using perl command?

The perl command offers extensive text processing capabilities, robust support for regular expressions, and a vast library of modules suitable for diverse tasks, from small scripting chores to large-scale projects, across various operating systems. However, perl’s flexible syntax can lead to readability challenges, especially in larger assignments. While perl may not match the performance of other languages for specific tasks, its popularity has declined with the rise of languages like Python and Ruby. Nevertheless, perl remains a valuable tool, particularly in fields such as bioinformatics, system administration, and web development.

Can I use perl for web development?

Yes, you can use perl for web development. It has frameworks like Mojolicious, Dancer, and Catalyst, along with modules like CGI.pm and mod_perl for building web applications and websites.

How do I debug perl scripts?

To debug Perl scripts, you can use options such as the -d option to invoke the Perl debugger and the -w option to enable warnings. Additionally, you can use modules like Data::Dumper for debugging data structures, while Carp is useful for error reporting and debugging.

Rate this post
Avatar photo

Md. Nafis Soumik graduated from the Bangladesh University of Engineering & Technology, Dhaka, with a BSc—Engg in Naval Architecture & Marine Engineering. In January 2023, Soumik joined Softeko as an Excel and VBA content developer. Since then, he has authored over 50 articles, spanning topics from fundamental to advanced Excel concepts such as Data Analysis and Manipulation, Data Visualization, Pivot Tables, Power Query, VBA, and so on. He participated in 2 specialized training programs on VBA and Chart & Dashboard design in Excel. Furthermore, he possesses a keen interest in Linux and currently serves as an executive content developer specializing in Linux. He aims to produce valuable content tailored to Linux users. During his leisure time, he enjoys music, traveling, and science documentaries. Read Full Bio

Leave a Comment