Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

strict.pm

by tye (Sage)
on Sep 13, 2000 at 22:46 UTC ( [id://32314]=modulereview: print w/replies, xml ) Need Help??

Item Description: Adds strictness that can make Perl code easier to maintain

Review Synopsis: Put "use strict;" near the top of any Perl code that you plan to keep

There are (currently) three options for "strictness". Though you should usually use all three by placing:

use strict;
near the top of each of your Perl files. This will help to make your source code easier to maintain.

use strict "vars"

If you use strict "vars", then you will get an error if you ever use a variable without "declaring" it. You can "declare" a variable via:

  • use vars qw( $scalar @array %hash );
  • my( $scalar, @array, %hash );
  • our( $scalar, @array, %hash ); (only for Perl 5.6 and higher).
  • Having the variable imported from a module (not common).
  • Including the package name in the variable name: $main::scalar

Detection of undeclared variables happens at compile time.

use strict "subs"

If you use strict "subs", then you will get an error for most uses of "barewords". Without this strictness, Perl will often interpret an unadorned identifier as a string:

print " ", Hello, ", ", World::ALL, "!\n"; # prints " Hello, World::ALL!"

It is good to use this strictness because forgetting to "adorn" an identifier is a common mistake. Perhaps you meant to write:

print " ", Hello(), ", ", $World::ALL, "!\n";

There are lots of ways to adorn an identifier so that it won't be a bareword:

  • Put it inside quotes or any of Perl's many other quoting operators.
  • Put $, @, %, or & in front of it.
  • Put parentheses after it (making it a function call).
  • Put : after it (making it a label).

And there are several ways you are expected to use barewords that will not be complained about even if you use strict "subs":

  • Reserved words (of course): print if "a" le $_ and not -s $_;
  • File handles: open(BAREWORD,"<$file"); print BAREWORD "Text\n";
  • Hash keys: $hash{bareword}
  • Hash keys in front of =>: %hash= ( bareword => "value" );
  • Declared subroutines (where use strict "subs" got its name). You can declare a subroutine several ways:
    • Import from a module:
      use Fcntl qw( LOCK_EX LOCK_NB ); flock FILE, LOCK_EX|LOCK_NB or die "File already locked"
    • Just define the subroutine before you use it:
      sub Log { warn localtime(), ": ", @_, "\n"; } Log "Ready.";
    • Predeclare the subroutine before you use it and then define it elsewhere:
      sub Log; Log "Ready."; sub Log { warn localtime(), ": ", @_, "\n"; }
      Note that you aren't protected from naming your subroutine "log" instead of "Log" which would result in you trying to take the natural logarithm of "Ready." in both of the examples above because just declaring a subroutine doesn't override built-in routines like log(). So it is a good idea to name subroutines with mixed letter case [you can also invoke your subroutine named "log" using &log("Ready.") but trying &log "Ready." won't work even if you have predeclared sub log as using & without parentheses is a special form of function invocation that takes no arguments, reusing the current values in @_ instead].
  • Package names used to invoke class methods:
    $o= My::Package->new();
    Here My::Package is usually a bareword. Note that this is a bit of an ambiguous case because you could have a subroutine called sub My::Package and the above code would be interpretted as:
    $o= My::Package()->new();
    which is why, for Perl5.6 and later, you may wish to write:
    $o= My::Package::->new();
    to avoid the ambiguity.

Detection of barewords happens at compile time. This is particularly nice because you can make a policy of making sure many of your subroutines are declared before you use them (especially in the case of constants which are usually imported from modules) and them call them as barewords (no parens and no &) and then Perl will detect typos in these names at compile time for you.

use strict "refs"

If you use strict "refs", then you will get an error if you try to access a variable by "computing" its name. This is called a symbolic reference. For example:

use vars qw( $this $that ); my $varname= @ARGV ? "this" : "that"; ${$varname}= "In use"; # This line uses a symbolic reference.

Symbolic references were often used in Perl4. Perl5 has real references (often created with the backslash operator, \) that should be used instead (or perhaps you should be using a hash and computing key names instead of computing variable names). Perl5 also has lexical variables (see the my operator) that can't be accessed via symbolic references. Catching symbolic reference is good because a common mistake is having a variable that should contain a real reference but doesn't. Dereferencing such a variable might silently fetch you garbage without this strictness.

Detection of using symbolic references happens at run time.

If you have one of those truely rare cases where you need to do symbolic references in Perl5, then you can delcare no strict "refs" for just that chunk of code or use eval.

Updated to cover a few more cases.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
RE: strict
by BastardOperator (Monk) on Sep 13, 2000 at 23:45 UTC
    damn fine review, I wish that more people would take the time to really explain things. "strict" is one of those good habits to get into, and it almost suprised me to see it reviewed, but then I realized how much it really needed to be. Thanks for a great job!
Re: strict.pm
by dsb (Chaplain) on Mar 01, 2001 at 00:35 UTC
    Very much enjoyed your review. I do, however, have some questions.

    1. I understand the idea of a symbolic reference, but I'm not sure how you'd go about creating one. I'd like to know that so I can avoid it. Might it be something like this:

    $a = "Amel"; $b = \$a; # $b is a 'hard' reference $c = $b; # $c is a 'symbolic' reference?
    Is this correct? The perlref docs say that a symbolic ref are names of other variables. So in the case above, is $c a symbolic ref because it merely holds as its value another variable that is a hard ref. Or is $c just a deeper hard ref?

    2. I looked up 'strict' in the Camel book and it said: "If no import list is given to use 'strict;', all possible restrictions upon unsafe Perl constructs are imposed." My question is: What exactly is an unsafe construct, and what is it that makes it unsafe?(OK that's 2 questions...sorry)

    I'm trying to better understand why 'strict' is safer. I use it all the time and the code I write is usually "safe", but I don't know why it would be unsafe.

    Thanks for all your help.

    Amel - f.k.a. - kel

      You create a symbolic reference like this:

      $a= "this";
      Doesn't look like a symbolic reference, does it? But it is. It isn't the creating of symbolic references that is a problem; it is using symbolic references. You use a symbolic reference just like you use a regular reference. So:
      $b= $$a;
      is where we have a problem. But it is only a problem if $a doesn't contain a real (non-symbolic) reference. That is why use of symbolic references (and not creation of them) is only caught at run time.

      Like I said elsewhere, "unsafe" doesn't make a lot of sense to me in discussing strict.pm. strict.pm helps Perl to catch things that are probably simple programmer mistakes. By catching them explicitly, you usually save time in trying to find the mistake and fix it.

              - tye (but my friends call me "Tye")
Re: strict
by wardk (Deacon) on Dec 10, 2000 at 08:27 UTC
    we should get to vote for this one twice.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: modulereview [id://32314]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2024-04-18 17:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found