Posts in the “perl” category

Perl printing examples

Perl printing FAQ: Can you share some Perl printing examples?

There are several different ways to print in Perl, and I thought I'd share some examples here today.

The Perl print function

Generally you'll print simple output with the Perl print function. As a simple example, you can print a string literal using the Perl print function, like this:

Perl: How to access shell environment variables through Perl associative arrays

Perl shell environment variables FAQ: How can I access Unix shell environment variables from a Perl script?

One of the great features of the Perl language is it's support of associative arrays. Unlike normal arrays, whose subscripts can only be integers, the subscripts of associative arrays are text strings. This may not sound like much yet, but with associative arrays (or hashes as they're now called) we can create fairly complex data structures with Perl.

Perl best practice: prefer foreach to for

Perl problem: When you don't use Perl every day, it's hard to remember the combination of the for loop syntax and how to deal with the special $_ variable to refer to each element within the body of the loop.

Solution: As I write this today, I still can't remember how to get this for loop and $_ syntax to work, at least not without pulling out a book, or looking it up on the internet. A much better solution is to just use Perl's foreach syntax, and never look back.

Perl: How to test if a file exists

Perl file exists FAQ: How can I perform a test to see if a file exists with Perl?

You can test to see if a file exists with the Perl "-e" file operator.

A Perl file exists example

Here's a short test/example:

Perl CSV file column extraction

Perl CSV column data extraction FAQ: Can you share an example of how to extract one or more columns from a Perl CSV file or other similarly-formatted flat text file?

Perl is a terrific language for text processing, but several readers have written wondering about how to extract columns of data from text files with Perl. For instance, when you have a text database that looks like this:

Perl array push and pop syntax and examples

Perl array push pop FAQ: How do I push elements onto a Perl array, and how do I pop element off a Perl array? (Or, What is the Perl push and pop syntax?)

I really like the Perl push (and Perl pop) syntax. The push function makes adding elements to a Perl array very easy, and the pop function also makes a Perl array work a lot like a stack.

Perl array/sort FAQ - Perl integer array sorting

Summary: How to sort Perl arrays, in this case, a Perl integer array.

Sorting a Perl integer array (technically a Perl numeric array) is relatively simple, well, at least once you know the magic formula. The key thing to know is that you need to provide the Perl sort function a helper function (or block of code) that tells it how to sort integers. By default, the Perl sort function sorts arrays in ASCII order, and that's not going to work very well for you.

Perl if, else, elsif ("else if") syntax

Summary: This tutorial shows a collection of Perl if, else, and else if examples.

Here are some examples of the Perl if/else syntax, including the “else if” syntax, which is really elsif. (I wrote this because after working with many different languages I can never remember the “else if” syntax for most languages, and elsif is pretty rare.)

The Perl if/else syntax

The Perl if/else syntax is standard, I don’t have any problems here:

How to use the Perl ternary operator

In most languages there is an operator named the "ternary" operator that lets you write concise if/then statements. This makes for less verbose, which is generally a good thing. Perl also has a ternary operator, and I'll demonstrate it here.

General syntax of the ternary operator

The general syntax for Perl's ternary operator looks like this:

test-expression ? if-true-expression : if-false-expression

Let's take a look at a brief example to demonstrate this.

How do I make variables private to my Perl function?

Perl function FAQ: How do I make variables private to my Perl function?

Answer: Just use the Perl my operator. Here's an example that shows how to create a variable named bar that is private to the function name foo:

How to access arguments to a Perl subroutine or function

Perl FAQ: How do I access the arguments that have been passed to my subroutine or function?

Answer: The special array @_ holds the values that are passed into a Perl subroutine/function, and you use that array to access those arguments. The first argument is represented by the variable $_[0], the second argument is represented by $_[1], and so on.

It may also help to know that number of elements passed in to your subroutine is given by the value of scalar(@_).

Put Perl test data in the same file as your source code

Perl test data FAQ: How can I store some sample/test data with my source code in Perl?

Answer: With Perl it's very easy to store some sample data in the same file as your Perl source code. Assuming you're creating a "main" Perl program (not a Perl module) you can use the special __END__ operator, and then include your data after that operator, as shown in my sample code below. You can then access that data using the main::DATA operator inside of a while loop.

Here's a quick sample program:

Perl file test operators (reference)

This document provides a list of the most commonly-used Perl file test operators.

Operators to determine whether a file or directory exists

Here are the most common Perl file test operators that can be used to determine whether a file or directory exists:

-e  File or directory name exists
-z  File exists and has zero size
-s  File or directory exists and has non-zero size

All of those tests can be executed as shown in the following source code example:

Perl delete - how to delete a file in a Perl script

You delete a file in Perl programs using the Perl unlink function. Let's take a look at a simple example.

A simple Perl delete (Perl unlink) example

First, we need a test file we can delete from our Perl script. Let's create a sample file in the current directory using the Unix touch command, like this:

touch delete-me.txt

(This creates an empty file named delete-me.txt.)

A Perl script to delete binary files

As a quick note and a little bit of source code sharing, I wrote the following Perl script to delete all of the binary files it finds in a list of files it’s given. I named this script, and it should be called like this: listOfFilesToLookAt

where listOfFilesToLookAt is a file that contains a list of filenames, with one filename per line.

Given that brief introduction, here’s the source code:

#!/usr/bin/perl -w

# ---------------------------------------------------------------
# this script takes a filename as input.
# that file should contain a list of all files (not directories)
#      that this script should examine.
# this script will delete all binary files that are in that list.
# ---------------------------------------------------------------

# 1) open the file that has a list of all of the files that need to be looked at.
#    get this filename from the command line.
$num_args = $#ARGV + 1;
if ($num_args != 1) {
    print "\nUsage: filename\n";

$listOfFiles = $ARGV[0];

# 2) now go through all of the files in that file.
#    if any of them are binary files, delete them.
open(FILE, $listOfFiles) or die "Could not read from '$listOfFiles', cowardly quitting. $!";

while (<FILE>) {
    $currFile = $_;
    if (-B $currFile) {
        unlink($currFile) or die "Could not delete '$currFile'\n";
        print "   deleted: $currFile\n";


Possibly the only two important things about this example are:

  • The -B file test operator determines if the current file is a binary file.
  • The Perl unlink function is used to delete a file.

I just thought I’d share this source code here, so as a quick summary, if you wanted to see some Perl source code that shows (a) how to check to see if a file is a binary file, and (b) how to delete files in Perl, I hope this is helpful

A Perl script to convert Nagios/Unix epoch time to a human readable format

I had to work with Nagios a lot this morning, in particular reading through the nagios.log log file. If you're ever read that log file, or looked at some other Linux/Unix log files, you've seen records that display the time in an epoch time format, which looks like this:


If you can read the epoch time format and know the actual human readable date and time, you're a better person than I am (or you've been looking at Nagios, Linux, or Unix log files too long).

Perl comparison operators

Perl equality FAQ: Can you share a list of the Perl equality operators?

Sure. Here's a convenient list of the Perl comparison operators (also known as Perl equality operators, equal, or not equal operators).

The Perl comparison operators are different for numeric and string comparison tests, as you can see in the following table:

How to exclude certain elements in an array with pattern matching

Problem: You have an array of elements, and you need to process every element in the array, except the elements that match a given regular expression (pattern).

Solution: You can solve this problem using a combination of the Perl regular expression pattern matching, along with the next operator.