use constant

use constant BUFFER_SIZE    => 4096;
use constant ONE_YEAR       => 365.2425 * 24 * 60 * 60;
use constant PI             => 4 * atan2 1, 1;
use constant DEBUGGING      => 0;
use constant ORACLE         => 'oracle@cs.indiana.edu';
use constant USERNAME       => scalar getpwuid($<);
use constant USERINFO       => getpwuid($<);

sub deg2rad { PI * $_[0] / 180 }

print "This line does nothing"      unless DEBUGGING;

# references can be declared constant
use constant CHASH          => { foo => 42 };
use constant CARRAY         => [ 1,2,3,4 ];
use constant CPSEUDOHASH    => [ { foo => 1}, 42 ];
use constant CCODE          => sub { "bite $_[0]\n" };

print CHASH->{foo};
print CARRAY->[$i];
print CPSEUDOHASH->{foo};
print CCODE->("me");
print CHASH->[10];                          # compile-time error

This pragma declares the named symbol to be an immutable constant[2] with the given scalar or list value. You must make a separate declaration for each symbol. Values are evaluated in list context. You may override this with scalar as we did above.

Since these constants don't have a $ on the front, you can't interpolate them directly into double-quotish strings, although you may do so indirectly:

print "The value of PI is @{[ PI ]}.\n";

Because list constants are returned as lists, not as arrays, you must subscript a list-valued constant using extra parentheses as you would any other list expression:

$homedir = USERINFO[7];             # WRONG
$homedir = (USERINFO)[7];           # ok

Although using all capital letters for constants is recommended to help them stand out and to help avoid potential collisions with ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.