fork download
  1. #!/usr/bin/perl
  2.  
  3. # Idiom #281 Use a Point as a map key
  4.  
  5. package Point {
  6. sub new { my $class = shift; bless { @_ }, $class }
  7.  
  8. sub x { shift->{x} };
  9. sub y { shift->{y} };
  10.  
  11. use overload '""' => sub { shift->_stringify() };
  12.  
  13. sub _stringify {
  14. my $self = shift;
  15. return sprintf "(%s, %s)", $self->x, $self->y;
  16. }
  17. }
  18.  
  19. my %m;
  20. my @points;
  21. foreach my $x (1..3) {
  22. foreach my $y (10..12) {
  23. my $p = Point->new(x => $x, y => $y);
  24. push @points, $p;
  25. $m{$p} = $p;
  26. }
  27. }
  28.  
  29. for (1..5) {
  30. my $r = $points[ int rand @points ];
  31. printf "picked point %s got point %s\n", $r, $m{$r};
  32. }
  33.  
  34.  
  35. # for the posted idiom
  36.  
  37. my %m;
  38. my $p = Point->new(x => 42, y => 5);
  39. $m{$p} = 'Hello';
  40.  
  41. print "$p = $m{$p}";
Success #stdin #stdout 0.01s 5532KB
stdin
Standard input is empty
stdout
picked point (2, 11) got point (2, 11)
picked point (1, 11) got point (1, 11)
picked point (3, 11) got point (3, 11)
picked point (3, 10) got point (3, 10)
picked point (3, 12) got point (3, 12)
(42, 5) = Hello