Constants

in Perl Tips, Miscellaneous
by William Ward on August 30, 2002 11:02 am

If your program uses certain values which are defined as global variables at the top of the program, and which are kept constant throughout the program (Example: a filename, hostname, URL, user ID, or some other static configuration value), consider using Perl’s "use constant" mechanism to define that value instead. Here’s what it looks like:

  use constant data_file => "/home/bill/data.txt";
  use constant pi        => 3.14159;

To use it, just put "data_file" (or whatever you want to name it) into an expression:

  open INPUT, data_file
      or die "Can't read ".data_file.": $!n";
  my $circumference = 2 * pi * $radius;

Note that since it is not a variable, you can’t use it inside a string. But you can use the concatenation operator (.) to join it with the other parts of the string.

What is the point? Well, for one thing, it prevents your program from accidentally modifying the value. There are a number of ways that you might inadvertently change the contents of a variable, but you can never change the contents of a constant.

How does it work? When you call "use constant" as above, you pass in a list of two scalars: the name of the constant and its value. (The "=>" operator is just a fancy comma, which allows you to omit the quotes on the word that precedes it.) The constant package actually creates a subroutine with the name you specified, and that subroutine returns the value given.

You might think that it would incur a performance penalty to use this mechanism - but Perl has an optimizer which can tell if all a subroutine does is return a constant value, and when it does, it "inlines" that subroutine. This means that as Perl compiles your program, every time you use "data_file" or any other constant, the value of that constant is substituted at compile time. So there’s no performance cost.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment