File Coverage

blib/lib/MARC/Record.pm
Criterion Covered Total %
statement 190 200 95.0
branch 56 66 84.8
condition 3 8 37.5
subroutine 35 36 97.2
pod 23 23 100.0
total 307 333 92.1


line stmt bran cond sub pod time code
1             package MARC::Record;
2              
3             =head1 NAME
4              
5             MARC::Record - Perl extension for handling MARC records
6              
7             =cut
8              
9 30     30   173457 use strict;
  30         104  
  30         1018  
10 30     30   5491 use integer;
  30         128  
  30         159  
11              
12 30     30   750 use vars qw( $ERROR );
  30         44  
  30         1222  
13              
14 30     30   9435 use MARC::Field;
  30         66  
  30         831  
15 30     30   176 use Carp qw(croak);
  30         47  
  30         1686  
16              
17             =head1 VERSION
18              
19             Version 1.39_02
20              
21             =cut
22              
23 30     30   147 use vars qw( $VERSION );
  30         44  
  30         1319  
24             $VERSION = '1.39_02';
25              
26 30     30   138 use Exporter;
  30         43  
  30         1112  
27 30     30   153 use vars qw( @ISA @EXPORTS @EXPORT_OK );
  30         37  
  30         2027  
28             @ISA = qw( Exporter );
29             @EXPORTS = qw();
30             @EXPORT_OK = qw( LEADER_LEN );
31              
32 30     30   127 use vars qw( $DEBUG ); $DEBUG = 0;
  30         42  
  30         1196  
33              
34 30     30   132 use constant LEADER_LEN => 24;
  30         41  
  30         51694  
35              
36             =head1 DESCRIPTION
37              
38             Module for handling MARC records as objects. The file-handling stuff is
39             in MARC::File::*.
40              
41             =head1 ERROR HANDLING
42              
43             Any errors generated are stored in C<$MARC::Record::ERROR>.
44             Warnings are kept with the record and accessible in the C method.
45              
46             =head1 CONSTRUCTORS
47              
48             =head2 new()
49              
50             Base constructor for the class. It just returns a completely empty record.
51             To get real data, you'll need to populate it with fields, or use one of
52             the MARC::File::* modules to read from a file.
53              
54             =cut
55              
56             sub new {
57 390     390 1 4420 my $class = shift;
58 390         1500 my $self = {
59             _leader => ' ' x 24,
60             _fields => [],
61             _warnings => [],
62             };
63 390         1891 return bless $self, $class;
64             } # new()
65              
66             =head2 new_from_usmarc( $marcblob [, \&filter_func($tagno,$tagdata)] )
67              
68             This is a wrapper around C for compatibility with
69             older versions of MARC::Record.
70              
71             The C is optional. See L::decode for details.
72              
73             =cut
74              
75             sub new_from_usmarc {
76 2     2 1 20 my $blob = shift;
77 2 50 33     22 $blob = shift if (ref($blob) || ($blob eq "MARC::Record"));
78              
79 2         740 require MARC::File::USMARC;
80              
81 2         10 return MARC::File::USMARC::decode( $blob, @_ );
82             }
83              
84             =head1 COMMON FIELD RETRIEVAL METHODS
85              
86             Following are a number of convenience methods for commonly-retrieved
87             data fields. Please note that they each return strings, not MARC::Field
88             objects. They return empty strings if the appropriate field or subfield
89             is not found. This is as opposed to the C/C methods
90             which return C if something's not found. My assumption is that
91             these methods are used for quick & dirty reports and you don't want to
92             mess around with noting if something is undef.
93              
94             Also note that no punctuation cleanup is done. If the 245a is
95             "Programming Perl / ", then that's what you'll get back, rather than
96             "Programming Perl".
97              
98             =head2 title()
99              
100             Returns the title from the 245 tag.
101              
102             =cut
103              
104             sub title() {
105 11     11 1 3859 my $self = shift;
106              
107 11         41 my $field = $self->field(245);
108 11 100       90 return $field ? $field->as_string : "";
109             }
110              
111             =head2 title_proper()
112              
113             Returns the title proper from the 245 tag, subfields a, n and p.
114              
115             =cut
116              
117             sub title_proper() {
118 11     11 1 1962 my $self = shift;
119              
120 11         37 my $field = $self->field(245);
121              
122 11 100       40 if ( $field ) {
123 9         27 return $field->as_string('anp');
124             } else {
125 2         11 return "";
126             }
127             }
128              
129             =head2 author()
130              
131             Returns the author from the 100, 110 or 111 tag.
132              
133             =cut
134              
135             sub author() {
136 6     6 1 2056 my $self = shift;
137              
138 6         29 my $field = $self->field('100|110|111');
139 6 100       45 return $field ? $field->as_string : "";
140             }
141              
142             =head2 edition()
143              
144             Returns the edition from the 250 tag, subfield a.
145              
146             =cut
147              
148             sub edition() {
149 6     6 1 13 my $self = shift;
150              
151 6         23 my $str = $self->subfield(250,'a');
152 6 100       41 return defined $str ? $str : "";
153             }
154              
155             =head2 publication_date()
156              
157             Returns the publication date from the 260 tag, subfield c.
158              
159             =cut
160              
161             sub publication_date() {
162 6     6 1 16 my $self = shift;
163              
164 6         16 my $str = $self->subfield(260,'c');
165 6 100       38 return defined $str ? $str : "";
166             }
167              
168             =head1 FIELD & SUBFIELD ACCESS METHODS
169              
170             =head2 fields()
171              
172             Returns a list of all the fields in the record. The list contains
173             a MARC::Field object for each field in the record.
174              
175             =cut
176              
177             sub fields() {
178 256     256 1 3038 my $self = shift;
179 256         235 return @{$self->{_fields}};
  256         828  
180             }
181              
182             =head2 field( I )
183              
184             Returns a list of tags that match the field specifier, or an empty
185             list if nothing matched. In scalar context, returns the first
186             matching tag, or undef if nothing matched.
187              
188             The field specifier can be a simple number (i.e. "245"), or use the "."
189             notation of wildcarding (i.e. subject tags are "6..").
190              
191             =cut
192              
193             my %field_regex;
194              
195             sub field {
196 232     232 1 60897 my $self = shift;
197 232         458 my @specs = @_;
198              
199 232         272 my @list = ();
200 232         376 for my $tag ( @specs ) {
201 232         362 my $regex = $field_regex{ $tag };
202              
203             # Compile & stash it if necessary
204 232 100       515 if ( not defined $regex ) {
205 44         681 $regex = qr/^$tag$/;
206 44         129 $field_regex{ $tag } = $regex;
207             } # not defined
208              
209 232         469 for my $maybe ( $self->fields ) {
210 1312 100       2324 if ( $maybe->tag =~ $regex ) {
211 217 100       929 return $maybe unless wantarray;
212              
213 6         14 push( @list, $maybe );
214             } # if
215             } # for $maybe
216             } # for $tag
217              
218 21 100       105 return unless wantarray;
219 4         14 return @list;
220             }
221              
222             =head2 subfield( $tag, $subfield )
223              
224             Shortcut method for getting just a subfield for a tag. These are equivalent:
225              
226             my $title = $marc->field('245')->subfield("a");
227             my $title = $marc->subfield('245',"a");
228              
229             If either the field or subfield can't be found, C is returned.
230              
231             =cut
232              
233             sub subfield {
234 16     16 1 945 my $self = shift;
235 16         23 my $tag = shift;
236 16         25 my $subfield = shift;
237              
238 16 100       31 my $field = $self->field($tag) or return;
239 9         65 return $field->subfield($subfield);
240             } # subfield()
241              
242             =for internal
243              
244             =cut
245              
246             sub _all_parms_are_fields {
247 2382     2382   3444 for ( @_ ) {
248 2397 100       8244 return 0 unless ref($_) eq 'MARC::Field';
249             }
250 2378         5079 return 1;
251             }
252              
253             =head2 append_fields( @fields )
254              
255             Appends the field specified by C<$field> to the end of the record.
256             C<@fields> need to be MARC::Field objects.
257              
258             my $field = MARC::Field->new('590','','','a' => 'My local note.');
259             $record->append_fields($field);
260              
261             Returns the number of fields appended.
262              
263             =cut
264              
265             sub append_fields {
266 2368     2368 1 5819 my $self = shift;
267              
268 2368 100       3439 _all_parms_are_fields(@_) or croak('Arguments must be MARC::Field objects');
269              
270 2367         2189 push(@{ $self->{_fields} }, @_);
  2367         4771  
271 2367         15184 return scalar @_;
272             }
273              
274             =head2 insert_fields_before( $before_field, @new_fields )
275              
276             Inserts the field specified by C<$new_field> before the field C<$before_field>.
277             Returns the number of fields inserted, or undef on failures.
278             Both C<$before_field> and all C<@new_fields> need to be MARC::Field objects.
279             If they are not an exception will be thrown.
280              
281             my $before_field = $record->field('260');
282             my $new_field = MARC::Field->new('250','','','a' => '2nd ed.');
283             $record->insert_fields_before($before_field,$new_field);
284              
285             =cut
286              
287             sub insert_fields_before {
288 7     7 1 871 my $self = shift;
289              
290 7 100       25 _all_parms_are_fields(@_)
291             or croak('All arguments must be MARC::Field objects');
292              
293 6         10 my ($before,@new) = @_;
294              
295             ## find position of $before
296 6         9 my $fields = $self->{_fields};
297 6         8 my $pos = 0;
298 6         10 foreach my $f (@$fields) {
299 68 100       99 last if ($f == $before);
300 63         57 $pos++;
301             }
302              
303             ## insert before $before
304 6 100       23 if ($pos >= @$fields) {
305 1         2 $self->_warn("Couldn't find field to insert before");
306 1         2 return;
307             }
308 5         18 splice(@$fields,$pos,0,@new);
309 5         10 return scalar @new;
310              
311             }
312              
313             =head2 insert_fields_after( $after_field, @new_fields )
314              
315             Identical to C, but fields are added after
316             C<$after_field>. Remember, C<$after_field> and any new fields must be
317             valid MARC::Field objects or else an exception will be thrown.
318              
319             =cut
320              
321             sub insert_fields_after {
322 3     3 1 1340 my $self = shift;
323              
324 3 100       10 _all_parms_are_fields(@_) or croak('All arguments must be MARC::Field objects');
325 2         4 my ($after,@new) = @_;
326              
327             ## find position of $after
328 2         4 my $fields = $self->{_fields};
329 2         2 my $pos = 0;
330 2         4 foreach my $f (@$fields) {
331 32 100       46 last if ($f == $after);
332 30         26 $pos++;
333             }
334              
335             ## insert after $after
336 2 50       6 if ($pos+1 >= @$fields) {
337 0         0 $self->_warn("Couldn't find field to insert after");
338 0         0 return;
339             }
340 2         6 splice(@$fields,$pos+1,0,@new);
341 2         6 return scalar @new;
342             }
343              
344             =head2 insert_fields_ordered( @new_fields )
345              
346             Will insert fields in strictly numerical order. So a 008 will be filed
347             after a 001 field. See C for an additional ordering.
348              
349             =cut
350              
351             sub insert_fields_ordered {
352 2     2 1 4 my ( $self, @new ) = @_;
353              
354 2 50       7 _all_parms_are_fields(@new)
355             or croak('All arguments must be MARC::Field objects');
356              
357             ## go through each new field
358 2         4 NEW_FIELD: foreach my $newField ( @new ) {
359              
360             ## find location before which it should be inserted
361 4         5 EXISTING_FIELD: foreach my $field ( @{ $self->{_fields} } ) {
  4         16  
362 4 100       7 if ( $field->tag() >= $newField->tag() ) {
363 2         5 $self->insert_fields_before( $field, $newField );
364 2         4 next NEW_FIELD;
365             }
366             }
367              
368             ## if we fell through then this new field is higher than
369             ## all the existing fields, so we append.
370 2         9 $self->append_fields( $newField );
371              
372             }
373 2         7 return( scalar( @new ) );
374             }
375              
376             =head2 insert_grouped_field( $field )
377              
378             Will insert the specified MARC::Field object into the record in grouped
379             order and return true (1) on success, and false (undef) on failure.
380              
381             my $field = MARC::Field->new( '510', 'Indexed by Google.' );
382             $record->insert_grouped_field( $field );
383              
384             For example, if a '650' field is inserted with C
385             it will be inserted at the end of the 6XX group of tags. After discussion
386             most people wanted the ability to add a new field to the end of the
387             hundred group where it belonged. The reason is that according to the MARC
388             format, fields within a record are supposed to be grouped by block
389             (hundred groups). This means that fields may not necessarily be in tag
390             order.
391              
392             =cut
393              
394             sub insert_grouped_field {
395 2     2 1 858 my ($self,$new) = @_;
396 2 100       5 _all_parms_are_fields($new) or croak('Argument must be MARC::Field object');
397              
398             ## try to find the end of the field group and insert it there
399 1         4 my $limit = int($new->tag() / 100);
400 1         2 my $found = 0;
401 1         3 foreach my $field ($self->fields()) {
402 14 100       24 if ( int($field->tag() / 100) > $limit ) {
403 1         4 $self->insert_fields_before($field,$new);
404 1         1 $found = 1;
405 1         2 last;
406             }
407             }
408              
409             ## if we couldn't find the end of the group, then we must not have
410             ## any tags this high yet, so just append it
411 1 50       4 if (!$found) {
412 0         0 $self->append_fields($new);
413             }
414              
415 1         3 return(1);
416              
417             }
418              
419              
420             =head2 delete_field( $field )
421              
422             Deletes a field from the record.
423              
424             The field must have been retrieved from the record using the
425             C method. For example, to delete a 526 tag if it exists:
426              
427             my $tag526 = $marc->field( "526" );
428             if ( $tag526 ) {
429             $marc->delete_field( $tag526 );
430             }
431              
432             C returns the number of fields that were deleted.
433             This shouldn't be 0 unless you didn't get the tag properly.
434              
435             =cut
436              
437             sub delete_field {
438 3     3 1 444 my $self = shift;
439 3         4 my $deleter = shift;
440 3         4 my $list = $self->{_fields};
441              
442 3         2 my $old_count = @$list;
443 3         6 @$list = grep { $_ != $deleter } @$list;
  58         63  
444 3         7 return $old_count - @$list;
445             }
446              
447             =head2 as_usmarc()
448              
449             This is a wrapper around C for compatibility with
450             older versions of MARC::Record.
451              
452             =cut
453              
454             sub as_usmarc() {
455 7     7 1 1928 my $self = shift;
456              
457 7         1088 require MARC::File::USMARC;
458              
459 7         26 return MARC::File::USMARC::encode( $self );
460             }
461              
462             =head2 as_formatted()
463              
464             Returns a pretty string for printing in a MARC dump.
465              
466             =cut
467              
468             sub as_formatted() {
469 14     14 1 4734 my $self = shift;
470              
471 14   50     92 my @lines = ( "LDR " . ($self->{_leader} || "") );
472 14         18 for my $field ( @{$self->{_fields}} ) {
  14         39  
473 193         336 push( @lines, $field->as_formatted() );
474             }
475              
476 14         128 return join( "\n", @lines );
477             } # as_formatted
478              
479              
480             =head2 leader()
481              
482             Returns the leader for the record. Sets the leader if I is defined.
483             No error checking is done on the validity of the leader.
484              
485             =cut
486              
487             sub leader {
488 393     393 1 1231 my $self = shift;
489 393         990 my $text = shift;
490              
491 393 100       1044 if ( defined $text ) {
492 381 100       1234 (length($text) eq 24)
493             or $self->_warn( "Leader must be 24 bytes long" );
494 381         989 $self->{_leader} = $text;
495             } # set the leader
496              
497 393         1281 return $self->{_leader};
498             } # leader()
499              
500             =head2 set_leader_lengths( $reclen, $baseaddr )
501              
502             Internal function for updating the leader's length and base address.
503              
504             =cut
505              
506             sub set_leader_lengths {
507 8     8 1 42 my $self = shift;
508 8         35 my $reclen = shift;
509 8         13 my $baseaddr = shift;
510 8         27 substr($self->{_leader},0,5) = sprintf("%05d",$reclen);
511 8         17 substr($self->{_leader},12,5) = sprintf("%05d",$baseaddr);
512             # MARC21 defaults: http://www.loc.gov/marc/bibliographic/ecbdldrd.html
513 8         15 substr($self->{_leader},10,2) = '22';
514 8         33 substr($self->{_leader},20,4) = '4500';
515             }
516              
517             =head2 clone()
518              
519             The C method makes a copy of an existing MARC record and returns
520             the new version. Note that you cannot just say:
521              
522             my $newmarc = $oldmarc;
523              
524             This just makes a copy of the reference, not a new object. You must use
525             the C method like so:
526              
527             my $newmarc = $oldmarc->clone;
528              
529             You can also specify field specs to filter down only a
530             certain subset of fields. For instance, if you only wanted the
531             title and ISBN tags from a record, you could do this:
532              
533             my $small_marc = $marc->clone( 245, '020' );
534              
535             The order of the fields is preserved as it was in the original record.
536              
537             =cut
538              
539             sub clone {
540 1     1 1 5 my $self = shift;
541 1         2 my @keeper_tags = @_;
542              
543             # create a new object of whatever type we happen to be
544 1         2 my $class = ref( $self );
545 1         8 my $clone = $class->new();
546              
547 1         3 $clone->{_leader} = $self->{_leader};
548              
549 1 50       3 my $filtered = @keeper_tags ? [$self->field( @keeper_tags )] : undef;
550              
551 1         4 for my $field ( $self->fields() ) {
552 18 50 33     35 if ( !$filtered || (grep {$field eq $_} @$filtered ) ) {
  0         0  
553 18         37 $clone->append_fields( $field->clone );
554             }
555             }
556              
557             # XXX FIX THIS $clone->update_leader();
558              
559 1         4 return $clone;
560             }
561              
562             =head2 warnings()
563              
564             Returns the warnings (as a list) that were created when the record was read.
565             These are things like "Invalid indicators converted to blanks".
566              
567             my @warnings = $record->warnings();
568              
569             The warnings are items that you might be interested in, or might
570             not. It depends on how stringently you're checking data. If
571             you're doing some grunt data analysis, you probably don't care.
572              
573             A side effect of calling warnings() is that the warning buffer will
574             be cleared.
575              
576             =cut
577              
578             sub warnings() {
579 14     14 1 4152 my $self = shift;
580 14         22 my @warnings = @{$self->{_warnings}};
  14         42  
581 14         32 $self->{_warnings} = [];
582 14         63 return @warnings;
583             }
584              
585             =head2 add_fields()
586              
587             C is now deprecated, and users are encouraged to use
588             C, C, and C
589             since they do what you want probably. It is still here though, for backwards
590             compatability.
591              
592             C adds MARC::Field objects to the end of the list. Returns the
593             number of fields added, or C if there was an error.
594              
595             There are three ways of calling C to add data to the record.
596              
597             =over 4
598              
599             =item 1 Create a MARC::Field object and add it
600              
601             my $author = MARC::Field->new(
602             100, "1", " ", a => "Arnosky, Jim."
603             );
604             $marc->add_fields( $author );
605              
606             =item 2 Add the data fields directly, and let C take care of the objectifying.
607              
608             $marc->add_fields(
609             245, "1", "0",
610             a => "Raccoons and ripe corn /",
611             c => "Jim Arnosky.",
612             );
613              
614             =item 3 Same as #2 above, but pass multiple fields of data in anonymous lists
615              
616             $marc->add_fields(
617             [ 250, " ", " ", a => "1st ed." ],
618             [ 650, "1", " ", a => "Raccoons." ],
619             );
620              
621             =back
622              
623             =cut
624              
625             sub add_fields {
626 2068     2068 1 2050 my $self = shift;
627              
628 2068         1898 my $nfields = 0;
629 2068         2341 my $fields = $self->{_fields};
630              
631 2068         3885 while ( my $parm = shift ) {
632             # User handed us a list of data (most common possibility)
633 2077 100       3139 if ( ref($parm) eq "" ) {
    50          
    50          
634 2067 50       4728 my $field = MARC::Field->new( $parm, @_ )
635             or return _gripe( $MARC::Field::ERROR );
636 2067         2799 push( @$fields, $field );
637 2067         1761 ++$nfields;
638 2067         2737 last; # Bail out, we're done eating parms
639              
640             # User handed us an object.
641             } elsif ( ref($parm) eq "MARC::Field" ) {
642 0         0 push( @$fields, $parm );
643 0         0 ++$nfields;
644              
645             # User handed us an anonymous list of parms
646             } elsif ( ref($parm) eq "ARRAY" ) {
647 10 50       29 my $field = MARC::Field->new(@$parm)
648             or return _gripe( $MARC::Field::ERROR );
649 10         14 push( @$fields, $field );
650 10         22 ++$nfields;
651              
652             } else {
653 0         0 croak( "Unknown parm of type", ref($parm), " passed to add_fields()" );
654             } # if
655              
656             } # while
657              
658 2068         7109 return $nfields;
659             }
660              
661             # NOTE: _warn is an object method
662             sub _warn {
663 15     15   23 my $self = shift;
664 15         19 push( @{$self->{_warnings}}, join( "", @_ ) );
  15         60  
665 15         43 return( $self );
666             }
667              
668              
669             # NOTE: _gripe is NOT an object method
670             sub _gripe {
671 0     0     $ERROR = join( "", @_ );
672              
673 0           warn $ERROR;
674              
675 0           return;
676             }
677              
678              
679             1;
680              
681             __END__