Perl Newbies

  1. Perl
  2. Modules
  3. here

strict - strictify grammar check

strict module strictify Perl grammar checking.

use strict;

strict module strictify Perl syntax checking. Make sure to write strict module when you write Perl program in current days. If an undeclared variable is used and you run the script, program stops with compile error messages.

Description of strict module

Let's see the effects of strict module. strict module has a certain effect.

Force variable declaration

The first effect is forcing variable declaration. In Perl, variables declared using my are called lexical variables. If you use strict module, you force variable declaration using my.

use strict;

# No error occurs because the variable is declared
my $num;
$num = 1
use strict;

# An error occurs because variable is used without declaration using my
$num2 = 2

In the second example, the program ends without excecution and the following error message is showed.

Global symbol "$num2" requires explicit package name at a.pl line 4.

This message means undeclared variable "$num2" is used at a.pl line 4 on effects of strict module.

Forbid using barewords

The second effect of strict module is forbidding using barewords. Bareword means not quoted string. Perl allows you to use barewords if strict module is not enabled. If you enable strict module, using barewords is forbidden.

use strict;

# No error because the string is quoted
my $str = 'abcde';
use strict;

# An error occurs because the string is bareword.
my $str = abcde;

In the second example, the program ends with the following error message.

Bareword "abcde" not allowed while "strict subs" in use at a.pl line 3.

Forbid symbolic references

The third effect of strict module is forbid symbolic references. Perl has a feature called symbolic references. strict module forbids using symbolic references.

A symbolic reference is a feature that you can access a variable or a function using a string.

Look at the script below.

# Addition function
sub total {
  my ($num1, $num2) = @_;
  
  return $num1 + $num2;
}

# Symbolic reference
my $num = &{'total'}(1 + 2);

print $num;

This program has total function. Instead of calling “total(1 + 2)”, this program calls total function by using symbolic reference "&{'total'} (1 + 2)".

If strict module is enabled, this programu ends with the following message.

Can't use string ("total") as a subroutine ref while "strict refs" in use at a.pl line 11.

Sometimes you may need to use symbolic references. For example, when you want to define subroutines dynamically. In such a case, you can allow using symbolic references.

use strict;

# Allow using symbolic references
no strict 'refs';

strict module has three effects: "force variable declaration", "forbid barewords" and "forbid symbolic references".

Menu