Perl Newbies

  1. Perl
  2. Modules
  3. here

warnings module

warnings module enables warnings.

use warnings;

In Perl, by default, no warning is output to stderr. warnings module enables warnings. warnings is output to stderr if warnings occur. When you write Perl program in current days, be sure to use warnings module with strict module.

Variouse warnings

Here are some warnings you will offten see.

Using undefined values

A warning message is output to stderr if an undefined value is used. In the following program, an undefined value is used in print function.

use warnings;

# Use undefined value
my $str;
print $str;

If you run this program, you will see the following warning.

Use of uninitialized value $str in print at a.pl line 6

This means that undefined value $str is used in print function.

If you see warnings, fix the program. The program has some mistakes.

The string is not encoded

When you print multibyte string such as Japanese, you may see a warning that the string is not encoded.

The following program outputs a warning to stderr.

use warnings;
use utf8;

# The string is not encoded
my $str = 'こんにちは';
print $str;

You will see the following warning.

Wide character in print at a.pl line 7.

This means that print function prints an unencoded string. Let's encode the string properly.

use warnings;
use utf8;
use Encode 'encode';

# The string is not encoded
my $str = 'こんにちは';
print encode('UTF-8', $str);

The subroutine is redefined

If you define a subroutine more than once, you will see a warning that the subroutine is redefined.

The following program outputs a warning to stderr.

use warnings;

# Redefine subroutine
sub one { 1 }
sub one { 1 }

You will see the following warning.

Subroutine one redefined at a.pl line 5.

If you see a redefinition warning, the program maybe has some mistakes, but sometimes you want to replace the before subroutine. In such cases, you can suppress this warning.

no warnings 'redefine';

You write the above, the redefinition warning is not output to stderr.

use warnings;
no warnings 'redefine';

# No redefined warning occur
sub one { 1 }
sub one { 1 }
Menu