X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2Fconstant.pm;h=5d3dd91b46f94f01999fd9eed46aab737dfe0ed8;hb=4499d6b9d14594604210bc28005c5e4ab2e49947;hp=4416cf2ade5df748e79d325bc06c02bdbc8d1f60;hpb=acce7d4e04d89207299003c3e80c69d50bc82069;p=p5sagit%2Fp5-mst-13.2.git diff --git a/lib/constant.pm b/lib/constant.pm index 4416cf2..5d3dd91 100644 --- a/lib/constant.pm +++ b/lib/constant.pm @@ -20,6 +20,18 @@ constant - Perl pragma to declare constants 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 + =head1 DESCRIPTION This will declare a symbol to be a constant with the given scalar @@ -80,11 +92,14 @@ B that value in the current implementation. Magical values, tied values, and references can be made into constants at compile time, allowing for way cool stuff like this. +(These error numbers aren't totally portable, alas.) use constant E2BIG => ($! = 7); print E2BIG, "\n"; # something like "Arg list too long" print 0+E2BIG, "\n"; # "7" +Errors in dereferencing constant references are trapped at compile-time. + =head1 TECHNICAL NOTE In the current implementation, scalar constants are actually @@ -105,6 +120,15 @@ name as a constant. This is probably a Good Thing. Unlike constants in some languages, these cannot be overridden on the command line or via environment variables. +You can get into trouble if you use constants in a context which +automatically quotes barewords (as is true for any subroutine call). +For example, you can't say C<$hash{CONSTANT}> because C will +be interpreted as a string. Use C<$hash{CONSTANT()}> or +C<$hash{+CONSTANT}> to prevent the bareword quoting mechanism from +kicking in. Similarly, since the C<=E> operator quotes a bareword +immediately to its left you have to say C 'value'> +instead of C 'value'>. + =head1 AUTHOR Tom Phoenix, EFE, with help from @@ -126,7 +150,7 @@ use vars qw($VERSION); #======================================================================= # Some of this stuff didn't work in version 5.003, alas. -require 5.003_20; +require 5.003_96; #======================================================================= # import() - import symbols into user's namespace