Perl confusing examples

  1. Confusing output order:

    use warnings; use strict; use 5.010;

    print 'OK'; my $x; say $x; $x = 42; say $x;

This code prints statements before the line generating the warning, the result might be confusing:

Use of uninitialized value $x in say at perl_warning_1.pl line 7.
OK
42

The reason is that by default Perl buffers STDOUT, while not buffer STDERR.

Turn off the buffering of STDOUT by: $| = 1; at the beginning of the script.

  1. Second most common warning: Use of uninitialized value:

Usually means variables have no value: either it never got a value, or at some point undef was assigned to it.

  1. Unknown warning category 'xxxx':

    use strict; use warnings

    print "Hello World";

Missing semicolon after using warnings statement. Perl is executing the print function and returns 1 indicating that is was successfull. changed to:

use warnings 1
  1. Boolean values in Perl:

    The number 0, the strings '0' and '', the empty list "()", and "undef" are all false in a boolean context. All other values are true. Negation of a true value by "!" or "not" returns a special false value. When evaluated as a string it is treated as '', but as a number, it is treated as 0.

References: Perl Maven Tutorial

Leave a comment

About flymike

user-pic Keep it simple, stupid.