constant::Atom

Unique symbols
Download

constant::Atom Ranking & Summary

Advertisement

  • Rating:
  • License:
  • Perl Artistic License
  • Price:
  • FREE
  • Publisher Name:
  • Jonathan R. Warden
  • Publisher web site:
  • http://search.cpan.org/~johnwrdn/

constant::Atom Tags


constant::Atom Description

Unique symbols Unlike constants declared with constant, Atoms are not associated with any specific scalar value. Instead, Atoms have their own independent identity, and will only compare positively (via the 'eq' test) with other identical Atoms. All other operations on Atoms are undefined, including casting to a number and casting to a string.Atoms are used in place of constants in situations where a unique value is needed to represent some idea or program state, but where that value is not naturally associated with a scalar value, and shouldn't be confused with one. Atoms are similar to C enums in this respect, except that Atoms do not have an ordinal value.Below is an example of where an Atom would solve a problem:# use constant::Atom 'error'; use constant 'error' => 999999; sub bar { my($arg) = @_; #Always return $arg for demonstration purposes (not error). return 1 ? $arg : error; } my $foo = bar(999999); print "Foo: $foo\n"; print $foo eq error ? "Foo returned error." : "Foo returned $foo.";Output: Foo returned error.In the above example, the programmer is trying to choose some unlikely value to alias 'error' to. The problem is, if 'bar' is ever accidently called with this same value, the program will mistakenly believe that 'error' had been returned.This doesn't happen with Atoms. use constant::Atom 'error';# use constant 'error' => 999999; sub bar { my($arg) = @_; #Always return $arg for demonstration purposes (not error). return 1 ? $arg : error; } my $foo = bar(999999); print "Foo: $foo\n"; print $foo eq error ? "Foo returned error." : "Foo returned $foo.";Output: Foo returned 999999.SYNOPSIS use constant::Atom qw (red yellow blue); my $color = red; print "Just as we thought!\n" if $color eq red; print "This will never happen.\n" if $color eq blue; print "Atoms never equal strings!\n" if $color eq 'red'; print "Color is ".$color->name."\n"; #The following raises an exception, because addition isn't defined for Atom objects. $color + 1; Requirements: · Perl


constant::Atom Related Software