Skip to Content
Programming Perl, 4th Edition
book

Programming Perl, 4th Edition

by Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
February 2012
Intermediate to advanced
1184 pages
37h 17m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 4th Edition

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($<);

use constant {
    BUFFER_SIZE    => 4096,
    ONE_YEAR       => 365.2425 * 24 * 60 * 60,
    PI             => 4 * atan2( 1, 1 ),
    DEBUGGING      => 0,
    ORACLE         => 'oracle@cs.indiana.edu',
    USERNAME       => scalar getpwuid($<),
    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 CCODE          => sub { "bite $_[0]\n" };

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

This pragma declares the named symbol to be an immutable constant[261] with the given scalar or list value. Values are evaluated in list context. You may override this with scalar as we did above. Giving it a hash reference declares many constants at once with only one use statement.

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]; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9781449321451Supplemental ContentErrata Page