fork download
  1. #!/usr/bin/perl
  2. # Idiom #282 Use a custom type as map key
  3. # https://p...content-available-to-author-only...s.org/idiom/282/use-a-custom-type-as-map-key/6042/perl
  4.  
  5. use v5.10;
  6. use Data::Dumper;
  7.  
  8. package Foo {
  9. use Scalar::Util 'refaddr';
  10.  
  11. use overload '""' => sub { shift->_stringify() };
  12.  
  13. sub _stringify {
  14. my $self = shift;
  15. my $x = $self->x;
  16. return "object $x: " . refaddr $self;
  17. }
  18. sub x { my $self = shift; $self->{x} // '' };
  19.  
  20. sub new { my $class = shift; return bless { @_ }, $class }
  21. };
  22.  
  23. my $p = Foo->new(x => 5);
  24. say '$p->x is ', $p->x;
  25.  
  26. my %map;
  27.  
  28. $map{$p} = 'some data';
  29.  
  30. say Dumper \%map;
  31.  
Success #stdin #stdout 0.02s 6996KB
stdin
Standard input is empty
stdout
$p->x is 5
$VAR1 = {
          'object 5: 94063102878328' => 'some data'
        };