What’s use strict; in Perl?

Brief overview of Perl's safety mechanism.

Share This Post

Many unseasoned Perl programmers or people who never really dove into the Practical Extraction and Report Language think it’s an ugly language, or at least a dangerous one. And it actually can be… but not all is lost!

use strict; is a Perl pragma which essentially keeps you from shooting yourself on the foot. It tells Perl to make you declare your variables, use lexicals, and basically make your write your programs in a way that they won’t eventually get you fired.

print $var;

Hello World

Note that in the snippet above we added my just before the variable. This tells Perl that $var will be valid in the outer-most block of code. Since there are no (explicit) blocks, it makes $var act like a global variable.  Now, suppose you need to reuse the variable name inside another block of code, this what you would get:

#!/usr/bin/perl -w

use strict;

my $var = "Hello World\n";

print $var;

{
    my $var = "A new value\n";
    print $var;
}

print $var;

Hello World

A new value

Hello World

There are some scenarios where you might have trouble with use strict; and might want to cheat a bit… in that case, you can do it with no strict; or its variance containing what you don’t want to be strict on: no strict ‘vars’; or no strict ‘subs’;

If you’re interested, you can find more pragmas here.

More To Explore

Documentation
vinny

bbPress Notify (No-Spam) Documentation

bbPress Notify (No-Spam) Documentation The bbPress Notify (No-Spam) is a free plugin that lets you control who gets notifications of new Topics and Replies in

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.