Values in Perl

Perl has various value types including strings, integers, floats, booleans, etc. Here are a few basic examples.

#!/usr/bin/env perl
use strict;
use warnings;

# Strings, which can be concatenated with '.'
print "perl" . "lang" . "\n";

# Integers and floats
print "1+1 = " . (1 + 1) . "\n";
print "7.0/3.0 = " . (7.0 / 3.0) . "\n";

# Booleans, with logical operators as you'd expect
print (1 && 0) ? "true" : "false", "\n";
print (1 || 0) ? "true" : "false", "\n";
print !1 ? "true" : "false", "\n";

To run the program, save it as values.pl and use the perl command:

$ perl values.pl
perllang
1+1 = 2
7.0/3.0 = 2.33333333333333
false
true
false

In this Perl example:

  1. We use the strict and warnings pragmas for better code quality and error reporting.

  2. String concatenation is done with the . operator instead of +.

  3. Perl doesn’t have a built-in boolean type. Instead, it uses a concept of “truthy” and “falsy” values. 0, ‘0’, undef, and empty strings are considered false; all other values are true.

  4. We use the ternary operator (?:) to convert the boolean results to “true” or “false” strings for printing.

  5. Logical operators in Perl are && (and), || (or), and ! (not), similar to many other languages.

  6. Perl automatically converts between strings and numbers as needed, so we don’t need to explicitly declare variable types.

This example demonstrates basic value types and operations in Perl, showing how it handles strings, numbers, and boolean logic.