Simple Things
Syndicate: full/short
Article Calendar
<= May, 2012
Search this blog

Key links
External Blogs
Brought to you by ...

Logical Operators

Andrew L. Johnson (First published by 2001-09-27)

Perl has operators to perform logical OR/AND/NOT operations, and they come in two forms: a high precedence symbolic form: ||, &&, !, and a low precedence form: or, and, not (respectively).

Logical AND and OR are binary operators and are often used to combine expressions in a conditional statement:

    if ($value > 5 && $value < 10) {
        print "$value is between 5 and 10 exclusive\n";

    if (lc($input) eq 'q' || lc($input) eq 'quit'){
        warn "Quitting application now\n";

The NOT operator is a unary operator that returns the negated (opposite) truth value of its argument:

    if ( not $done ) {                  # also: if(!$done){
        print "We are not finished\n";

Often we can use either the high or low precedence forms, however, occasionally precedence matters — consider the following mistaken expression and how the logical test is actually parsed:

    if (not $a && not $b) {
        print "\$a and \$b are false\n";

The programmer wanted to test that both $a AND $b were false. If $a is false then not($a) would be true, and similarly for $b, but this expression obviously fails. That is because the precedence of && is much higher than the precedence of ‘not’ so the expression is actually parsed as:

    if ( not ($a && (not $b)) ) {

which is not what was intended. We could fix this in a few different ways: either use the lower precedence form of AND (‘and’), or the higher precedence form of ‘not’:

    if ( !$a && !$b) {

    if (not $a and not $b) {

A more interesting aspect of the logical AND and OR is that they short-circuit their second operand if they do not need to check it to determine the truth or falsity of the entire expression:

    $a = 0;
    $b = 1;
    if ($a and $b) { print "Both a and b are true\n" }

In the above situation, Perl knows that for the an AND operation to be true, both sides must be true — if the left side is false then Perl doesn’t bother checking the right side (it already knows the whole expression must be false). This short-circuit, or lazy evaluation comes in handy in various situations outside of conditional tests — one of which you should be familiar with:

    open(FILE, $file) or die "Can't open $file: $!";

The open() function returns a true value when it succeeds. Perl knows that only one expression must be true for an OR operation to succeed, so if the left expression is true Perl ignores the right hand side. In this case, that means the right hand side is only evaluated if the file could not be opened (in which case, the die() function is called).

Repeating Yourself: The x Operator

Andrew L. Johnson (First published by 2001-09-20)

Loops are the general mechanism for expressing repetition in code. However, there are a couple of instances where loops seem like overkill — repeating strings and repeating lists. For these cases, Perl provides the repetition operator (the ‘x’ operator).

In the case of a repeated string we may simply want to print out lines of 20 ’-’ characters (perhaps as boundary lines in a report). Doing this with a loop is not difficult, though a little cumbersome given the task:

    print "This is the Header\n";
    print '-' for 1 .. 20;
    print "\n";

The x operator allows us to build this string in a single operation:

    print "This is the Header\n";
    print '-' x 20, "\n";

The x operator is a binary operator (takes two operands) and is context sensitive both in terms of the context of the entire operation, and in terms of the context of the left operand). The basic syntax is:

    Left-EXPR x Right-EXPR

The right expression (right operand) is always considered to be in scalar context and treated as an integer. The left expression (left operand) may be either a scalar or a list value.

When the left operand is a scalar, as in the example above, the x operator treats it as a string and returns a new string repeated by the number given as the right operand. So, ’-’ x 20 returns a string of 20 ’-’ characters, and ‘foo’ x 2 returns the string ‘foofoo’. This evaluation remains the same whether the entire expression is in scalar context or in list context — in the example above the expression is an argument to the print() function and therefore in list context.

The x operator can return repeated lists if used in list context and if the left operand is a literal list (ie, wrapped in parentheses):

    my @array = (1,2,3) x 2;
    print "@array"           # prints: 1 2 3 1 2 3

You need to be careful to put the left operand in parentheses for list repetition — using a plain array will not behave as desired:

    my @array = (1,12,42);
    @array = @array x 2;
    print "@array\n";       # prints: 33

In this case, because the left operand is not in parentheses it is evaluated as a scalar, and an array in scalar context returns the number of elements in the array — in this case 3 — thus the x operator has returned the string ‘3’ repeated twice.

Is this operator practical? Consider a case where you want to define a ten element array and initialize each element to 1:

    my @array = (1) x 10; #  my @array = (1,1,1,1,1,1,1,1,1,1);

Another useful case is initializing a hash when we’ve read in (or otherwise obtained) a list of keys we wish to initialize to 1:

    my @keys = qw(a b c d);
    my %hash;
    @hash{@keys} = (1) x @keys;

Lastly, a minor cautionary note — remember that ‘x’ is not the multiplication operator:

    my $value = 15 x 2 / 3;
    print "$value\n";       # prints: 505

Here the number 15 is treated as a string and repeated twice to get 1515 which is then treated as a number and divided by 3 to get 505 (rather than the result of 10 you might have wanted). This is one case where Perl’s natural conversion between numbers and strings without warning can mean that a simple typo (‘x’ instead of ’*’) can lead to strange results and be difficult to track down. So, if you have calculations in your code and you are getting bizarre results you might want to check for this particular typo.


Deleting Elements from An Array

Andrew L. Johnson (First published by 2001-09-13)

There are two things one might mean by ‘deleting’ elements from an array: deleting the value for a particular index (or indices) in the array (while still leaving the slot in the array open), or, actually removing a slot (and its contents) from the array. The first case can be accomplished with the delete() function, and the second with the splice function.

    my @array = (0,1,2,3,4,5,6);
    delete $array[3];
    print join(':', @array),"\n";

    splice(@array, 3, 1);
    print join(':', @array),"\n";

This snippet produces the following output:

    Use of uninitialized value in join or string at - line 3.

You can see that the delete() function only deletes the value at index 3 in the array, while the splice() function removes the slot entirely and shifts the remainder of the array down to fill in the gap.

The delete() function can also be used on an array slice as well as a single element — and that slice need not be a contiguous range of elements:

    # delete a range
    delete @array[0..3];
    # or a discontiquous slice
    delete @array[0,3,5];

The splice() function may also be used to remove a range of elements from an array, but not a discontiguous slice:

    splice(@array,0,3);  # remove 3 elements starting at index 0.

One may think that the delete() function (formerly only allowed on hash elements) is nothing more than simply undef()’ing elements in an array, or assigning either multiple undef values to multiple elements or perhaps assigning an empty list to multiple values:

    my @array = (0,1,2,3,4,5,6);
    $array[0] = undef;
    @array[1,2] = ();
    @array[3,4] = (undef,undef);
    print join(':', @array),"\n";

which prints (ignoring warnings):


This is what we’d expect if we’d used delete() as well. However, the methods are not entirely equivalent. The delete() function has a companion exists() function (also formerly only used with hashes) that detects the difference between and array element that has been deleted and one that has been undefined:

    my @array = (0,1,2,3,4,5,6);
    @array[0,3,5] = (undef,undef,undef);
    print "1: Still there\n" if exists $array[3];
    @array[0,3,5] = ();
    print "2: Still there\n" if exists $array[3];
    delete @array[0,3,5];
    print "3: Still there\n" if exists $array[3];

Which produces:

    1: Still there
    2: Still there

So even though a given element is undefined (ie, the defined() function would return false), Perl can still tell if it has been delete()’ed or not. In many situations the delete() function applied to an array element or slice is no better than the other methods shown, and somewhat slower. But, some algorithms may find it useful to be able to determine if the value of an array element is undefined because it was assigned an undefined value or because it was intentionally deleted.

This discussion brings up one additional warning: assigning an empty list to an array slice does not remove any array elements (it merely assigns an undefined value to the slice elements). Thus the following two statements do not produce the same result (even if it might seem that they are logically equivalent):

    my @array = (0,1,2,3,4,5,6);
    @array[0..$#array] = ();
    print join(':', @array),"\n";

    my @array = (0,1,2,3,4,5,6);
    @array = ();
    print join(':', @array),"\n";

Even though the first snippet assigns an empty list to a slice covering the entire array, the array slots themselves are still considered to be in the array. The second snippet assigns the empty list to the array itself and therefore results in an empty array.


Iterating Over the Fibonacci Numbers

Andrew L. Johnson (First published by 2001-09-06)

Consider the Fibonacci numbers (0,1,1,2,3,5,8,13,21,34,…), where the next number is the sum of the previous two in the series. We could create a recursive routine to calculate these:

    #!/usr/bin/perl -w
    use strict;

    sub fib {
      my $n = shift;
      return $n if $n < 2;
      fib($n-1) + fib($n-2);

    for(0..9) {
        print fib($_),"\n";

However, a problem with this approach is that sue to its recursive nature, the fib() routine must recalculate earlier numbers in the series every time it is called. One simple solution is to create a cache to store numbers in the series and have the function use those if they exist This is called Memoization and there is a Memoize module on CPAN (we discussed this module back in May 2001). This technique is a trade off between using more space (the cache) and gaining more speed.

If one only wishes to iterate through the series in order (perhaps with breaks to do other processing) then another solution is to create an iterator using a closure:

    #!/usr/bin/perl -w
    use strict;
    sub gen_fib {
        my($curr, $next) = (0,1);
        return sub {
            my $fib = $curr;
            ($curr, $next) = ($next, $curr + $next);
            return $fib;

    my $fib_stream1 = gen_fib();
    my $fib_stream2 = gen_fib();

    # print first 5 Fibonacci numbers from stream 1
    print "Stream One:";
        print $fib_stream1->(), ' ';
    print "\n";

    # print first 10 from stream 2
    print "Stream Two:";
    for (1..10) {
        print $fib_stream2->(), ' ';
    print "\n";

    # print next 5 from stream 1
    print "Stream One:";
        print $fib_stream1->(), ' ';
    print "\n";

Some advantages of this technique are that it only stores enough state to calculate the next number (without recursion) rather than all the previous numbers in the series as memoization does, and you can have more than one independent iterator (or stream) in the same program. Disadvantages are that it is only useful in cases where you actually want to iterate through the series — it is not useful for calculating the Nth Fibonacci number (which the recursive solution could be used for).

You do not have to iterate over mathematical functions, you can iterate over anything — it is possible to create an iterator that iterates over N arrays in n-tuples (ie, get the first item from each array, then the second, …). With an array of array refs as a table, this is analogous to iterating over the columns rather than the rows.

Subroutine References as Closures

Andrew L. Johnson (First published by 2001-08-30)

A closure is a tricky kind of thing to explain, but not terribly hard to understand. The following may not meet with computer science approval as an explanation of closures, but the examples should provide enough hands-on exposure to grasp underlying concept.

The first thing we need to understand is that named subroutines are global by nature — that is, the subroutine name (identifier) lives in the package’s symbol table. However, they run within the lexical scope they were defined within:

    #!/usr/bin/perl -w
    use strict;

        my $inc = 10;
        sub incr {
            print "$inc\n";



In the above, $inc is lexically scoped within the block, and the subroutine (incr()) is defined within the same block. We can not refer to $inc after the block (scope) is finished, but we can call the subroutine and it runs in the scope it was defined in so it can still access $inc and change it.

A closure is simply an anonymous subroutine that is bound to the lexical scope it was defined within (rather like the above situation.

    #!/usr/bin/perl -w
    use strict;

    sub make_incr {
        my $inc = shift;
        return sub {print "$inc\n"; $inc++};

    my $c1 = make_incr(10);
    my $c2 = make_incr(20);


Our make_incr() routine is a closure generator — it takes an argument and creates a new lexical variable. It then returns an anonymous subroutine that uses this same variable. Each time we call this routine a new lexical $inc is created and the anonymous subroutine refers to that particular copy of $inc. Each closure generated ($c1 and $c2) have their own private copies of $inc to work with. Essentially, they each can save information about their current state (in this case, what number they are currently at).

Here is another simple example (adapted from my book) where the closure itself also takes an argument:

    sub exclaim {
        my $prefix = shift;
        return sub {print "$prefix $_[0]!\n"};

    my $batman = exclaim('Indeed');
    my $robin  = exclaim('Holy');

    $robin->('Mackerel');   # prints: Holy Mackerel!
    $batman->('Robin');     # prints: Indeed Robin!

Closures can be useful for creating callback routines and iterators. The above example of make_incr() creates very simple iterators that simply count up by ones from a given base number. However, you can create an iterator to iterate through more complex functions as well. Next week we will discuss using a closure as an iterator over the Fibonacci numbers.