Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.0 KiB

  1. package Text::Abbrev;
  2. require 5.005; # Probably works on earlier versions too.
  3. require Exporter;
  4. =head1 NAME
  5. abbrev - create an abbreviation table from a list
  6. =head1 SYNOPSIS
  7. use Text::Abbrev;
  8. abbrev $hashref, LIST
  9. =head1 DESCRIPTION
  10. Stores all unambiguous truncations of each element of LIST
  11. as keys in the associative array referenced by C<$hashref>.
  12. The values are the original list elements.
  13. =head1 EXAMPLE
  14. $hashref = abbrev qw(list edit send abort gripe);
  15. %hash = abbrev qw(list edit send abort gripe);
  16. abbrev $hashref, qw(list edit send abort gripe);
  17. abbrev(*hash, qw(list edit send abort gripe));
  18. =cut
  19. @ISA = qw(Exporter);
  20. @EXPORT = qw(abbrev);
  21. # Usage:
  22. # abbrev \%foo, LIST;
  23. # ...
  24. # $long = $foo{$short};
  25. sub abbrev {
  26. my ($word, $hashref, $glob, %table, $returnvoid);
  27. if (ref($_[0])) { # hash reference preferably
  28. $hashref = shift;
  29. $returnvoid = 1;
  30. } elsif (ref \$_[0] eq 'GLOB') { # is actually a glob (deprecated)
  31. $hashref = \%{shift()};
  32. $returnvoid = 1;
  33. }
  34. %{$hashref} = ();
  35. WORD: foreach $word (@_) {
  36. for (my $len = (length $word) - 1; $len > 0; --$len) {
  37. my $abbrev = substr($word,0,$len);
  38. my $seen = ++$table{$abbrev};
  39. if ($seen == 1) { # We're the first word so far to have
  40. # this abbreviation.
  41. $hashref->{$abbrev} = $word;
  42. } elsif ($seen == 2) { # We're the second word to have this
  43. # abbreviation, so we can't use it.
  44. delete $hashref->{$abbrev};
  45. } else { # We're the third word to have this
  46. # abbreviation, so skip to the next word.
  47. next WORD;
  48. }
  49. }
  50. }
  51. # Non-abbreviations always get entered, even if they aren't unique
  52. foreach $word (@_) {
  53. $hashref->{$word} = $word;
  54. }
  55. return if $returnvoid;
  56. if (wantarray) {
  57. %{$hashref};
  58. } else {
  59. $hashref;
  60. }
  61. }
  62. 1;