PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Library-CallNumber-LC-0.22/lib/Library/CallNumber/LC.pm

#
Perl | 445 lines | 347 code | 84 blank | 14 comment | 30 complexity | ad738be4c9c9becc7bf4f1698131107f MD5 | raw file
  1. package Library::CallNumber::LC;
  2. use warnings;
  3. use strict;
  4. use Math::BigInt;
  5. =head1 NAME
  6. Library::CallNumber::LC - Deal with Library-of-Congress call numbers
  7. =head1 VERSION
  8. Version 0.22;
  9. =cut
  10. our $VERSION = '0.22';
  11. =head1 SYNOPSIS
  12. Utility functions to deal with Library of Congress Call Numbers
  13. use Library::CallNumber::LC;
  14. my $a = Library::CallNumber::LC->new('A 123.4 .c11');
  15. print $a->normalize; # normalizes for string comparisons.
  16. # gives 'A01234 C11'
  17. print $a->start_of_range; # same as "normalize"
  18. my $b = Library::CallNumber::LC->new('B11 .c13 .d11');
  19. print $b->normalize;
  20. # gives 'B0011 C13 D11'
  21. my @range = ($a->start_of_range, $b->end_of_range);
  22. # end of range is 'B0011 C13 D11~'
  23. # Get components suitable for printing (e.g., number and decimal joined, leading dot on first cutter)
  24. @comps = Library::CallNumber::LC->new('A 123.4 .c11')->components()
  25. # Same thing, but return empty strings for missing components (e.g., the cutters)
  26. @comps = Library::CallNumber::LC->new('A 123.4 .c11')->components('true');
  27. =head1 ABSTRACT
  28. Library::CallNumber::LC is mostly designed to do call number normalization, with the following goals:
  29. =over 4
  30. =item * The normalized call numbers are comparable with each other, for proper sorting
  31. =item * The normalized call number is a short as possible, so left-anchored wildcard searches are possible (e.g., searching on "A11*" should give you all the A11 call numbers)
  32. =item * A range defined by start_of_range and end_of_range should be correct, assuming that the string given for the end of the range is, in fact, a left prefix.
  33. =back
  34. That last point needs some explanation. The idea is that if someone gives a range of, say, A-AZ, what they really mean is A - AZ9999.99. The end_of_range method generates a key which lies immediately beyond the last possible key for a given starting point. There is no attempt to make end_of_range normalization correspond to anything in real life.
  35. =cut
  36. # Set up the prefix mapping for longints
  37. my %intmap;
  38. my $i = 0;
  39. foreach my $prefix (qw(a aa ab abc ac ae ag ah ai al am an anl ao ap aq arx as at aug aw awo ay az b bc bd bf bg bh bj bl bm bn bp bq br bs bt bu bv bx c cb cc cd ce cg cis cj cmh cmm cn cr cs ct cz d da daa daw db dc dd de df dff dg dh dj djk dk dkj dl doc dp dq dr ds dt dth du dx e ea eb ec ed ee ek ep epa ex f fb fc fem fg fj fnd fp fsd ft ful g ga gb gc gda ge gf gh gn gr gs gt gv h ha hb hc hcg hd he hf hfs hg hh hhg hj hjc hm hmk hn hq hs ht hv hx i ia ib iid ill ilm in ioe ip j ja jan jb jc jf jg jh jhe jj jk jkc jl jln jn jq js jv jx jz k kb kbm kbp kbq kbr kbu kc kd kdc kde kdg kdk kds kdz ke kea keb kem ken keo keq kes kf kfa kfc kfd kff kfg kfh kfi kfk kfl kfm kfn kfo kfp kfr kfs kft kfu kfv kfw kfx kfz kg kga kgb kgc kgd kge kgf kgg kgh kgj kgk kgl kgn kgq kgs kgt kgv kgx kh kha khc khd khf khh khk khp khq khu khw kit kj kja kjc kje kjg kjj kjk kjm kjn kjp kjq kjr kjs kjt kjv kjw kk kka kkb kkc kke kkf kkg kkh kki kkj kkm kkn kkp kkq kkr kks kkt kkv kkw kkx kky kkz kl kla klb kld kle klf klg klh klm kln klp klr kls klt klv klw km kmc kme kmf kmh kmj kmk kml kmm kmn kmo kmp kmq kmt kmu kmv kmx kn knc knd kne knf kng knh knk knl knm knn knp knq knr kns knt knu knw knx kny kp kpa kpc kpe kpf kpg kph kpj kpk kpl kpm kpp kps kpt kpv kpw kq kqc kqe kqg kqj kqk kqp kqw krb krc krg krm krn krp krr krs kru krv krx ks ksa ksc ksh ksj ksk ksl ksp kss kst ksv ksw ksx ksy kta ktd ktg ktj ktk ktl ktq ktr ktt ktu ktv ktw ktx kty ktz ku kuc kuq kvc kvf kvm kvn kvp kvq kvr kvs kvw kwc kwg kwh kwl kwp kwr kww kwx kz kza kzd l la law lb lc ld le lf lg lh lj ll ln lrm lt lv m may mb mc me mf mh mkl ml mpc mr ms mt my n na nat nax nb nc nd nda nds ne ner new ng nh nk nl nmb nn no nt nv nx ok onc p pa pb pc pcr pd pe pf pg ph phd pj pjc pk pl pm pn pnb pp pq pr ps pt pz q qa qb qc qd qe qh qk ql qm qp qr qry qu qv r ra rb rbw rc rcc rd re ref res rf rg rh rj rk rl rm rn rp rs rt rv rx rz s sb sd see sf sfk sgv sh sk sn sql sw t ta tc td tdd te tf tg tgg th tj tk tl tn tnj to tp tr ts tt tx tz u ua ub uc ud ue uf ug uh un use v va vb vc vd ve vf vg vk vla vm w wq x xp xx y yh yl yy z za zhn zz zzz)) {
  40. $intmap{$prefix} = $i;
  41. $i++;
  42. }
  43. # Regexp constants to deal with matching LC and variants
  44. my $lcregex = qr/^
  45. \s*
  46. (?:VIDEO-D)? # for video stuff
  47. (?:DVD-ROM)? # DVDs, obviously
  48. (?:CD-ROM)? # CDs
  49. (?:TAPE-C)? # Tapes
  50. \s*
  51. ([A-Z]{1,3}) # alpha
  52. \s*
  53. (?: # optional numbers with optional decimal point
  54. (\d+)
  55. (?:\s*?\.\s*?(\d+))?
  56. )?
  57. \s*
  58. (\d+[stndrh]*)? # optional extra numbering including suffixes (1st, 2nd, etc.)
  59. \s*
  60. (?: # optional cutter
  61. \.? \s*
  62. ([A-Z]) # cutter letter
  63. \s*
  64. (\d+ | \Z)? # cutter numbers
  65. )?
  66. \s*
  67. (?: # optional cutter
  68. \.? \s*
  69. ([A-Z]) # cutter letter
  70. \s*
  71. (\d+ | \Z)? # cutter numbers
  72. )?
  73. \s*
  74. (?: # optional cutter
  75. \.? \s*
  76. ([A-Z]) # cutter letter
  77. \s*
  78. (\d+ | \Z)? # cutter numbers
  79. )?
  80. (\s+.+?)? # everthing else
  81. \s*$
  82. /x;
  83. my $weird = qr/
  84. ^
  85. \s*[A-Z]+\s*\d+\.\d+\.\d+
  86. /x;
  87. # Class variables for top/bottom sort chars
  88. my $Topper = ' '; # must sort before 'A'
  89. my $Bottomer = '~'; # must sort after 'Z' and '9'
  90. =head1 CONSTRUCTORS
  91. =head2 new([call_number_text, [topper_character, [bottomer_character]]]) -- create a new object, optionally passing in the initial string, a "topper", and a "bottomer" (explained below)
  92. =cut
  93. sub new {
  94. my $proto = shift;
  95. my $class = ref($proto) || $proto;
  96. my $lc = shift || '';
  97. my $topper = shift;
  98. $topper = $Topper if !defined($topper); # ZERO is false but might be a reasonable value, so we need this more specific check
  99. my $bottomer = shift || $Bottomer;
  100. my $self = {
  101. callno => uc($lc),
  102. topper => $topper,
  103. bottomer => $bottomer
  104. };
  105. bless $self, $class;
  106. return $self;
  107. }
  108. =head1 BASIC ACCESSORS
  109. =head2 call_number([call_number_text])
  110. The text of the call number we are dealing with.
  111. =cut
  112. sub call_number {
  113. my $self = shift;
  114. if (@_) { $self->{callno} = uc(shift) }
  115. return $self->{callno};
  116. }
  117. =head2 topper([character])
  118. Specify which character occupies the 'always-sort-to-the-top' slots in the sort keys. Defaults to the SPACE character, but can reasonably be anything with an ASCII value lower than 48 (i.e. the 'zero' character, '0'). This can function as either a class or instance method depending on need.
  119. =cut
  120. sub topper {
  121. my $self = shift;
  122. my $topper = shift;
  123. if (ref $self) {
  124. $self->{topper} = $topper if $topper; # just myself
  125. return $self->{topper};
  126. } else {
  127. $Topper = $topper if $topper; # whole class
  128. return $Topper;
  129. }
  130. }
  131. =head2 bottomer([character])
  132. Specify which character occupies the 'always-sort-to-the-bottom' slots in the sort keys. Defaults to the TILDE character, but can reasonably be anything with an ASCII value higher than 90 (i.e. 'Z'). This can function as either a class or instance method depending on need.
  133. =cut
  134. sub bottomer {
  135. my $self = shift;
  136. my $bottomer = shift;
  137. if (ref $self) {
  138. $self->{bottomer} = $bottomer if $bottomer; # just myself
  139. return $self->{bottomer};
  140. } else {
  141. $Bottomer = $bottomer if $bottomer; # whole class
  142. return $Bottomer;
  143. }
  144. }
  145. =head1 OTHER METHODS
  146. =head2 components(boolean returnAll = false)
  147. @comps = Library::CallNumber::LC->new('A 123.4 .c11')->components($returnAll)
  148. Returns an array of the individual components of the call number (or undef if it doesn't look like a call number).
  149. Components are:
  150. =over 4
  151. =item * alpha
  152. =item * number (numeric.decimal)
  153. =item * cutter1
  154. =item * cutter2
  155. =item * cutter3
  156. =item * "extra" (anything after the cutters)
  157. =back
  158. The optional argument <I returnAll> (false by default) determines whether or not empty components (e.g.,
  159. extra cutters) get a slot in the returned list.
  160. =cut
  161. sub components {
  162. my $self = shift;
  163. my $returnAll = shift;
  164. my $lc = $self->{callno};
  165. return undef if ($lc =~ $weird);
  166. return undef unless ($lc =~ $lcregex);
  167. my ($alpha, $num, $dec, $othernum, $c1alpha, $c1num, $c2alpha, $c2num, $c3alpha, $c3num, $extra) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
  168. #combine stuff if need be
  169. if ($dec) {
  170. $num .= '.' . $dec;
  171. }
  172. no warnings;
  173. my $c1 = join('', $c1alpha, $c1num);
  174. my $c2 = join('', $c2alpha, $c2num);
  175. my $c3 = join('', $c3alpha, $c3num);
  176. $c1 = '.' . $c1 if ($c1 =~ /\S/);
  177. use warnings;
  178. my @return;
  179. foreach my $comp ($alpha, $num, $othernum, $c1, $c2, $c3, $extra) {
  180. $comp = '' unless (defined $comp);
  181. next unless ($comp =~ /\S/ or $returnAll);
  182. $comp =~ m/^\s*(.*?)\s*$/;
  183. $comp = $1;
  184. push @return, $comp;
  185. }
  186. return @return;
  187. }
  188. =head2 _normalize(call_number_text)
  189. Base function to perform normalization.
  190. =cut
  191. sub _normalize {
  192. my $self = shift;
  193. my $lc = uc(shift);
  194. my $topper = $self->topper;
  195. # return undef if ($lc =~ $weird);
  196. return undef unless ($lc =~ $lcregex);
  197. my ($alpha, $num, $dec, $othernum, $c1alpha, $c1num, $c2alpha, $c2num, $c3alpha, $c3num, $extra) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
  198. no warnings;
  199. my $class = $alpha;
  200. $class .= sprintf('%04s', $num) if $num;
  201. $class .= $dec if $dec;
  202. my $c1 = $c1alpha.$c1num;
  203. my $c2 = $c2alpha.$c2num;
  204. my $c3 = $c3alpha.$c3num;
  205. # normalize extra (most commonly years/numbering, benefits from padding)
  206. # this could be reduced to a four digit pad, as very, very few numbers
  207. # reach 10000, but we'll be conservative here (for now)
  208. $extra =~ s/^\s+//g;
  209. $extra =~ s/\.\s+/./g;
  210. $extra =~ s/(\d)\s*-\s*(\d)/$1-$2/g;
  211. $extra =~ s/(\d+)/sprintf("%05s", $1)/ge;
  212. $extra = $topper . $extra if ($extra ne ''); # give the extra less 'weight' for falling down the list
  213. # pad out othernum (again, conservatively)
  214. $othernum =~ s/(\d+)/sprintf("%05s", $1)/ge;
  215. return join($topper, grep {/\S/} ($class, $othernum, $c1, $c2, $c3, $extra));
  216. }
  217. =head2 normalize([call_number_text])
  218. Normalize the stored or passed call number as a sortable string
  219. =cut
  220. sub normalize {
  221. my $self = shift;
  222. my $lc = shift;
  223. $lc = $lc? uc($lc) : $self->{callno};
  224. return $self->_normalize($lc)
  225. }
  226. =head2 start_of_range([call_number_text])
  227. Alias for normalize
  228. =cut
  229. sub start_of_range {
  230. my $self = shift;
  231. return $self->normalize(@_);
  232. }
  233. =head2 end_of_range([call_number_text])
  234. Downshift an lc number so it represents the end of a range
  235. =cut
  236. sub end_of_range {
  237. my $self = shift;
  238. my $lc = shift;
  239. $lc = $lc? uc($lc) : $self->{callno};
  240. my $bottomer = $self->bottomer;
  241. return $self->_normalize($lc) . $bottomer;
  242. }
  243. =head2 toLongInt(call_number_text, num_digits)
  244. Attempt to turn a call number into an integer value. Possibly useful for fast range checks, although obviously not perfectly accurate. Optional argument I<$num_digits> can be used to control the number of digits used, and therefore the precision of the results.
  245. =cut
  246. my $minval = new Math::BigInt('0'); # set to zero until this code matures
  247. my $minvalstring = $minval->bstr;
  248. # this is a work in progress, with room for improvement in both exception
  249. # logic and overall economy of bits
  250. sub toLongInt {
  251. my $self = shift;
  252. my $lc = shift;
  253. my $num_digits = shift || 19; # 19 is a max-fit for 64-bits within our scope
  254. my $topper = $self->topper;
  255. my $bottomer = $self->bottomer;
  256. #print "$lc\n";
  257. my $topper_ord = ord($topper);
  258. my $long = $self->normalize($lc);
  259. return $minvalstring unless ($long);
  260. my ($alpha, $num, $rest);
  261. if ($long =~ /^([A-Z]+)(\d{4})(.*)$/) { # we have a 'full' call number
  262. ($alpha, $num, $rest) = (lc($1), $2, $3);
  263. } elsif ($long =~ /^([A-Z]+)(.*)$/) { # numberless class; generally invalid, but let it slide for now
  264. ($alpha, $rest) = (lc($1), $2);
  265. if ($rest =~ /^$bottomer/) { # bottomed-out class
  266. $num = '9999';
  267. } else {
  268. $num = '0000';
  269. }
  270. }
  271. my $class_int_string = '';
  272. if (defined($intmap{$alpha})) {
  273. $class_int_string .= $intmap{$alpha} . $num;
  274. } else {
  275. warn "Unknown prefix '$alpha'\n";
  276. return $minvalstring;
  277. }
  278. my $rest_int_string = '';
  279. my $bottomout;
  280. foreach my $char (split('', $rest)) {
  281. if ($char eq $bottomer) {
  282. $bottomout = 1;
  283. last;
  284. }
  285. $rest_int_string .= sprintf('%02d', ord($char) - $topper_ord);
  286. }
  287. $rest_int_string = substr($rest_int_string, 0, $num_digits - 7); # Reserve first seven digits for $alpha and $num
  288. if ($bottomout) {
  289. $rest_int_string .= '9' x (($num_digits - 7) - length($rest_int_string)); # pad it if need be
  290. } else {
  291. $rest_int_string .= '0' x (($num_digits - 7) - length($rest_int_string)); # pad it if need be
  292. }
  293. # print " $long => ", join('', @rv), "\n";
  294. my $longint = Math::BigInt->new($class_int_string . $rest_int_string);
  295. $longint->badd($minval);
  296. # warn "\n\n".$self->_normalize($lc)." = ".$longint->bstr." ( $class_int_string + $rest_int_string) \n\n";
  297. return $longint->bstr;
  298. }
  299. =head1 AUTHOR
  300. Current Maintainer: Dan Wells, C<< <dbw2 at calvin.edu> >>
  301. Original Author: Bill Dueber, C<< <dueberb at umich.edu> >>
  302. =head1 BUGS
  303. Please report any bugs or feature requests through the web interface at
  304. L<http://code.google.com/p/library-callnumber-lc/issues/list>. I will be
  305. notified, and then you'll automatically be notified of progress on your bug as
  306. I make changes.
  307. =head1 SUPPORT
  308. You can find documentation for this module with the perldoc command.
  309. perldoc Library::CallNumber::LC
  310. You can also look for information at the Google Code page:
  311. http://code.google.com/p/library-callnumber-lc/
  312. =head1 COPYRIGHT & LICENSE
  313. Copyright 2009 Bill Dueber, all rights reserved.
  314. Copyright 2011 Dan Wells, all rights reserved.
  315. This program is free software; you can redistribute it and/or modify it
  316. under the same terms as Perl itself and also under the new BSD license
  317. as described at http://www.opensource.org/licenses/bsd-license.php
  318. =cut
  319. 1; # End of Library::CallNumber::LC