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:

  • The number zero (0) means false
  • The string zero ('0' or "0") means false
  • The empty string ('') means false

As a corollary to this, many other things equate to true in Perl, including:

  • Non-zero numbers
  • Non-empty strings

Those are the basic Perl true and false rules. Let’s look at some true/false examples to help understand this a little more.

Sample Perl true/false program output

To help demonstrate these Perl true/false test conditions, I’ve written a small Perl test program. Here’s the source code for the program:

@truths = (0, "0", "", 1, "1", "foo");

for (@truths)
{
  if ($_) { printf("'%s' is true\n", $_);  }
  else    { printf("'%s' is false\n", $_); }
}

And here’s the output from the program:

'0' is false
'0' is false
'' is false
'1' is true
'1' is true
'foo' is true

(And finally, while I’m in the printf neighborhood, if you’re interested in learning more about printf, I just put together a printf reference page.)

Perl true/false summary

I hope these Perl true false examples have been helpful to you. If you have any other true/false examples you’d like to share, just leave a note in the Comments section below.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.