Posts in the “perl” category

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:

Perl ‘equals’ FAQ: What is true and false in Perl?

Perl true/false FAQ: What is true in Perl? What is false in Perl?

The Perl programming language is a little unusual in not having true and false boolean operators. Because of this, I can never seem to remember what equates to true and false in Perl, so I decided to create this page.

What is true/false in Perl

In short, the following elements evalue to false in Perl:

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 deleteBinaryFiles.pl, and it should be called like this:

deleteBinaryFiles.pl 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: deleteBinaryFiles.pl filename\n";
    exit;
}

$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>) {
    chomp;
    $currFile = $_;
    if (-B $currFile) {
        unlink($currFile) or die "Could not delete '$currFile'\n";
        print "   deleted: $currFile\n";
    }
}

close(FILE);

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:

1219822177

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.

Perl split function - process every word in a file

Problem: You're developing a Perl program, and you need to process ("do something with") every word in a text file within your program.

Solution: How you achieve this in the end depends on your meaning of "every word", but I'm going to go with a very simple definition, where I can use the Perl split function to break up each "word" that is surrounded by whitespace characters.

Where is Perl looking for modules to include?

I started working on a new Unix system yesterday -- an HP-UX system I've never worked on before -- and I quickly realized that I needed some Perl modules installed. While working with another person the question quickly came up, "How do you know where Perl is looking for currently installed modules?"

Perl: How to extract lines from the middle of a text file

A Perl program to extract lines from the middle of a file

I've always been a big fan of the Unix head and tail commands, but several times I have wanted to print a range of lines from the middle of a text file -- not just the beginning or end of a file. Not liking the available solutions, I wrote my own.

Here is the source code for a program named "extract.pl", which prints lines from a text file beginning at the start line you specify and ending at the stop line.