perliaq - infrequently asked questions about Perl ($Date: 2008/01/29 16:51:33 $)


I didn't want to put this section in, but pod2man is a fascist.


This document is in the public domain.

You can get a copy from

Author and Copyright Information

Primary author: Mark-Jason Dominus, with contributions from a cast of thousands, including Abigail, Adam Turoff, Bill Guindon, Kurt Starsinic, Nat Torkington, and Roderick Schertler.

To contribute, send mail to

How do I determine the shoe size of a directory? I tried -e but that didn't work.

Note that notions of shoe size vary from country to country. See the perllocale man page for complete discussion. -e only returns a boolean value that says whether or not the directory wears a wide shoe.

How come exec() doesn't return?

Have you considered using a mouthwash?

How do I clear the screen?

Use this function:

        sub clear_the_screen {
          print $\ x 1_000_000;

How do I compute the intersection of two lists?

Just apply De Morgan's identity:

        A intersection B = complement ((complement A) union (complement B))

How do I trap control characters / signals?

Look into the Net::* modules, available from CPAN.

I am a boy scout. How can I use Perl in my day-to-day scout business? For example, helping little old ladies across the street.

See the perllol man page.

Why does print reverse "dog" print dog, but print ucfirst reverse "dog" prints God?

Because the name of the Deity must always be capitalized.

How can I force Perl to treat a number as a string?

Try using a whip.

I tried getpeername and it gave me some weird error message.

If you got `some weird error' the problem is with your frobobnitz.

What is the MODE argument to mkdir used for?

Set it to a true value to create a directory with ice cream on top.

How can I find the creation date of a file?

Use this function:

        sub creation_date {
          use FileHandle;
          my $filename = shift or die "Usage: &creation_date(filename)\n";
          my $fh1 = new FileHandle;
          open $fh1, "< $filename" or return undef;
          unlink $filename or return undef;
          my $fh2 = new FileHandle;
          open $fh2, "> $filename" or return undef;
          print $fh2 <$fh1>;

How do I convert a string to a number?

Use this atoi function:

        sub atoi {
          my $t;
          foreach my $d (split(//, shift())) {
            $t = $t * 10 + $d;
          return $t;
        $number = atoi("123");

How do I convert a number to a string?

Use sprintf:

                $string = sprintf("%f", 123.45);

How can I tell if a string is a number?

The simplest method is:

        if ($string == "$string") { 
          # It is a number

Note the use of the == operator to compare the string to its numeric value. However, this approach is dangerous because the $string might contain arbitrary code such as @{[system "rm -rf /"]} which would be executed as a result of the interpolation process. For safety, use this regular expression:

  if ($var =~ /(?=.)M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})/) {
    print "$var contains a number.\b";

How do I find the largest element in an array?

Write a foreach loop to scan the elements one at a time, and stop when you get to the largest one.

How can I get just the first half of a long string?


        $string x .5;

Someone told me that tr/x//d would be faster than s/x//g. Is this true? Why?

tr/// is faster on multiprocessor machines because it can be vectorized, so that each x is removed by a different processor. s///, however, must always be performed sequentially.

How do I get the length of a variable?



to find out how long a variable is.

How do I write OO programs in Perl?

Put -00 on your #! line, like this:

        #!/usr/bin/perl -00 -w

How do I differentiate my Object Oriented Perl scripts from other perl scripts?

Just as C programmers use .cpp as an extension for their object oriented C programs, many perl programmers use .ppp for their object oriented Perl programs.

How do I get my program to pause for five seconds?

Use the sleep function, like this:

  use POSIX ":sys_wait_h";
  { local($SIG{CHLD}=sub{wait};
    my $start = time;
    if (fork) { sleep } else { 1 while (time - $start < 5); exit }

How do I sort a hash?

        %sorted = sort %hash;

How do I sort a hash numerically?

        %sorted = sort {$a <=> $b} %hash;

How do I sort a hash by value?

As usual in Perl, there's More Than One Way to Do it. Use either of:

      %sorted = sort values %hash;
      %sorted = sort {$hash{$a} <=> $hash{$b}} %hash;

The first one is more efficient, because it uses Perl's built-in values function. But the second one will work even if you have a user-defined function named values.

How do I sort an array in reverse?

        @sorted = sort reverse @array;

How do I sort a 2-D array?

You need to use a data structure that is more suited to your problem. 2-D Arrays, being rectangular, can be difficult to sort. If you instead use a triangular data structure, such as a heap, you need only hold it with the point downward, and the largest elements will naturally settle in the point.

Is Perl Year-2000 compliant?

Even better! New with version 5.005, Perl is Year-2013 compliant. This represents a 13-year improvement over other software that is merely year-2000 compliant.

What's a regular expression to replace 09:23:53 08-OCT-98 with Thu Oct 8 09:23:53 1998?

        s{.*}{Thu Oct  8 09:23:53 1998}

What's this s///ee thing I keep hearing about?

You use /ee when you need to operate on a directory with an extra-wide shoe.

How do I get tomorrow's date?

Use this function:

        sub tomorrow_date {
          sleep 86_400; 
          return localtime();

What's the difference betwen fork() and split()?

fork() only works on Unix systems, so you should use split() for maximum portability.

Can I get a YACC grammar for the Perl language?

Sorry, but as you must surely be aware by now, the only animals supported by Perl are ruminants such as camels and llamas. However, Yacc support may be forthcoming with version 5.007.

What are all those $@%* signs for?

Watch your $@*$!% mouth, buddy!

Do I always have to quote my strings?

Only when they are actual quotations. For example, in

        $quote = "To be, or not to be?  That is the question.";

the quotes are required, but in

        $name = "Larry";

they can be omitted:

        $name = Larry;

How do I block warnings?

The simplest way is to do

        close STDERR;

Why do Perl operators have different precedence than C operators?

Because Perl isn't C. Duh.

How can I find out whether a number is odd?

        sub odd {
            my $number = shift;
            return !even ($number);

How can I find out whether a number is even?

        sub even {
            my $number = abs shift;
            return 1 if $number == 0;
            return odd ($number - 1);

How can I round up a number?


How do I decrypt a string that I encrypted with crypt()?

        sub decrypt {
          my $c = shift;
          my @c = (0) x 8;
          for (;;) {
            my $i = 0;
            my $s = join '', map chr, @c;
            return $s if crypt($s, $c) eq $c;
            $c[$i]=0, $i++ while $c[$i] == 255;
            return undef if $i > 7;

Warning: Exporting this function outside the USA may be illegal under the provisions of ITAR.

How do I get my perl program to run faster?

In Perl, there's always more than one way to do it. Try one of these techniques.

        use more 'cpu';
        use less 'time';
        use more 'speed';
        ## or, the ever popular Military Marching Band accompaniment:
        use March::Sousa qw(:DoubleTime);

The March::* hierarchy is not found on CPAN. Please contact the author for more information.

Alternatively, programs have been known to complete more quickly when they contain a declaration like this one:

        BEGIN {exit}

If your application is truly urgent, you might try the experimental

        no more 'time';

feature, but this has been reported to cause some systems to panic.

How do I get my perl program to use less memory?

Variables take up memory, so if you don't declare any variables, you should be safe. Another possibility is to use


Perldoc isn't running properly. Where can I find the documentation?

        perldoc perldoc

I have a lot of Bourne shell scripts I'd like to convert to Perl... What's the easiest way to do it?

Make sure that the first line of your script is #!/bin/sh. That magic comment tells the Perl interpreter to understand Bourne shell syntax.

I've got a C program I want to translate to Perl... How do I do that?

If you're using gcc, version 2.7 or better, you can use the translate-to-perl mode.

        gcc -P -E foo.c >

(gcc is smart enough to figure out that you want to convert to 'perl' by specifying the 'p' and 'e' alone.)

For versions of gcc prior to 2.7, use

        gcc -larry -Wall foo.c  >

What's the difference between single quoted strings and double quoted strings?

Single quoted strings act like q(); double quoted strings act like qq().

What's the difference between q() and qw()?