Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Sep 262011
 

Enable Perl strict mode to restrict unsafe constructs

Answer:

In Perl, you can enforce using the strict mode to reduce the chance of nasty error, e.g.

$foo = 'bar';
print $foo;

If you run the above problem, it is completely valid.

# perl test.pl
bar

However, if you use the strict pragma

use strict;

$foo = 'bar';
print $foo;

And run the program again..

# perl test.pl
Global symbol "$foo" requires explicit package name at test.pl line 3.
Global symbol "$foo" requires explicit package name at test.pl line 4.
Execution of test.pl aborted due to compilation errors.

Since the $foo is not declared before the first use, so the compilation stopped. In modern Perl developements, it is recommended to alwasys use the strict pragma in order to write a better and maintainable program.

To fix the problem, you need to use the my keyword, e.g.

use strict;

my $foo = 'bar';
print $foo;

And run the program again. (Thanks Jeroen for the suggestion)

  2 Responses to “Enable Perl strict mode to restrict unsafe constructs”

  1. Why not give the solution?

    my $foo = 'bar';

  2. @Jeroen, thanks for your suggestion! Post updated. Thanks.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>