CLOSE

The only caveat to the use constant pragma is that constants cannot be directly used as keys to a hash table. For example:

  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. use constant PI => (atan2(1,0) * 2);
  7.  
  8. my %htable =
  9. (
  10. 2.7182 => "Euler's constant",
  11. PI => "Pi",
  12. 1.6180 => "golden ratio",
  13. );
  14.  
  15. print "keys = ( " . join(', ', keys %htable) . ")";
  16. print "\n";

This will print "keys = ( 1.618, PI, 2.7182 )" because the word "PI" in the context of a hash key is always interpreted as the string, not the constant symbol.

  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. use constant PI => (atan2(1,0) * 2);
  7.  
  8. my $x = PI;
  9. my %htable =
  10. (
  11. 2.7182 => "Euler's constant",
  12. $x => "Pi",
  13. 1.6180 => "golden ratio",
  14. );
  15.  
  16. print "keys = ( " . join(', ', keys %htable) . ")";
  17. print "\n";

This will correctly print "keys = ( 3.14159, 1.618, 2.7182 )" but is not very elegant.


CLOSE