File: Tutorial.pod

package info (click to toggle)
libmarc-record-perl 2.0.7-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 528 kB
  • sloc: perl: 2,698; makefile: 2
file content (1449 lines) | stat: -rw-r--r-- 49,097 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
=head1 NAME

MARC::Doc::Tutorial - A documentation-only module for new users of MARC::Record

=head1 SYNOPSIS

 perldoc MARC::Doc::Tutorial

=head1 INTRODUCTION

=head2 What is MARC?

The MAchine Readable Cataloging format was designed by the Library of
Congress in the late 1960s in order to allow libraries to convert their card
catalogs into a digital format. The advantages of having computerized card
catalogs were soon realized, and now MARC is being used by all sorts of
libraries around the world to provide computerized access to their collections.
MARC data in transmission format is optimized for processing by computers, so
it's not very readable for the normal human. For more about the MARC format,
visit the Library of Congress at http://www.loc.gov/marc/

=head2 What is this Tutorial?

The document you are reading is a beginners guide to using Perl to processing
MARC data, written in the 'cookbook' style. Inside, you will find recipes on
how to read, write, update and convert MARC data using the MARC::Record CPAN
package. As with any cookbook, you should feel free to dip in at any section
and use the recipe you find interesting. If you are new to Perl, you may
want to read from the beginning.

The document you are reading is distributed with the MARC::Record package,
however in case you are reading it somewhere else, you can find the latest
version at CPAN: http://www.cpan.org/modules/by-module/MARC/. You'll notice
that some sections aren't filled in yet, which is a result of this document
being a work in progress. If you have ideas for new sections please make a
suggestion to perl4lib: https://perl4lib.perl.org/.

=head2 History of MARC on CPAN

In 1999, a group of developers began working on MARC.pm to provide a Perl
module for working with MARC data. MARC.pm was quite successful since it
grew to include many new options that were requested by the Perl/library
community.  However, in adding these features the module swiftly outgrew its
own clothes, and maintenance and addition of new features became extremely
difficult. In addition, as libraries began using MARC.pm to process large MARC
data files (>1000 records) they noticed that memory consumption would skyrocket.
Memory consumption became an issue for large batches of records because
MARC.pm's object model was based on the 'batch' rather than the record... so
each record in the file would often be read into memory. There were ways of
getting around this, but they were not obvious. Some effort was made to
reconcile the two approaches (batch and record), but with limited success.

In mid 2001, Andy Lester released MARC::Record and MARC::Field which provided
a much simpler and maintainable package for processing MARC data with Perl.
As its name suggests, MARC::Record treats an individual MARC record as the
primary Perl object, rather than having the object represent a given set of
records. Instead of forking the two projects, the developers agreed to
encourage use of the MARC::Record framework, and to work on enhancing
MARC::Record rather than extending MARC.pm further. Soon afterwards,
MARC::Batch was added, which allows you to read in a large data file
without having to worry about memory consumption.

In Dec., 2004, the MARC::Lint module, an extension to check the validity of MARC
records, was removed from the MARC::Record distribution, to become a separately
distributed package. This tutorial contains examples for using MARC::Lint.


=head2 Brief Overview of MARC Classes

The MARC::Record package is made up of several separate packages. This
can be somewhat confusing to people new to Perl, or Object Oriented
Programming. However this framework allows easy extension, and is built
to support new input/output formats as their need arises. For a good
introduction to using the object oriented features of Perl, see
the perlboot documentation that came with your version of Perl.

Here are the packages that get installed with MARC::Record:

=over 4

=item MARC::Batch

A convenience class for accessing MARC data contained in an external file.

=item MARC::Field

An object for representing the indicators and subfields of a single MARC field.

=item MARC::Record

This primary class represents a MARC record, being a container for multiple MARC::Field objects.

=item MARC::Doc::Tutorial

This document!

=item MARC::File

A superclass for representing files of MARC data.

=item MARC::File::MicroLIF

A subclass of MARC::File for working with data encoded in the MicroLIF format.

=item MARC::File::USMARC

A subclass of MARC::File for working with data encoded in the USMARC format.

=back

=head2 Help Wanted!

It's already been mentioned but it's worth mentioning again:
MARC::Doc::Tutorial is a work in progress, and you are encouraged to submit
any suggestions for additional recipes via the perl4lib mailing list at
https://perl4lib.perl.org/. Also, patches and issue reports are welcome
at https://github.com/perl4lib/marc-perl.



=head1 READING

=head2 Reading a record from a file

Let's say you have a USMARC record in 'file.dat' and
you'd like to read in the record and print out its title.

   1   ## Example R1
   2
   3   ## create a MARC::Batch object.
   4   use MARC::Batch;
   5   my $batch = MARC::Batch->new('USMARC', 'file.dat');
   6
   7   ## get a MARC record from the MARC::Batch object.
   8   ## the $record will be a MARC::Record object.
   9   my $record = $batch->next();
  10
  11   ## print the title contained in the record.
  12   print $record->title(),"\n";

Using the distribution's 't/camel.usmarc', your result should be:

  ActivePerl with ASP and ADO / Tobias Martinsson.

=head2 Iterating through a batch file

Now imagine that 'file.dat' actually contains multiple records and
we want to print the title for each of them. Our program doesn't have
to change very much at all: we just need to add a loop around our call
to C<next()>.

   1   ## Example R2
   2
   3   ## create a MARC::Batch object.
   4   use MARC::Batch;
   5   my $batch = MARC::Batch->new('USMARC','file.dat');
   6
   7   while (my $record = $batch->next()) {
   8
   9     ## print the title contained in the record.
  10     print $record->title(),"\n";
  11
  12   }

The call to the C<next()> method at line 7 returns the next record from the
file. C<next()> returns C<undef> when there are no more records left in the file,
which causes the C<while> loop to end. This is a useful idiom for reading in
all the records in a file. Your results with 'camel.usmarc' should be:

  ActivePerl with ASP and ADO / Tobias Martinsson.
  Programming the Perl DBI / Alligator Descartes and Tim Bunce.
  .
  .
  .
  Cross-platform Perl / Eric F. Johnson.

=head2 Checking for errors

It is a good idea to get in the habit of checking for errors. MARC/Perl has
been designed to help you do this. Calls to C<next()> when iterating through a
batch file will return C<undef> when there are no more records to return...
B<AND> when an error was encountered (see the next recipe to subvert this).
You probably want to make sure that you didn't abruptly stop reading a
batch file because of an error.

   1   ## Example R3
   2
   3   ## create a MARC::Batch object.
   4   use MARC::Batch;
   5   my $batch = MARC::Batch->new('USMARC','file.dat');
   6
   7   ## get a marc record from the MARC::Batch object.
   8   ## $record will be a MARC::Record object.
   9   while ( my $record = $batch->next() ) {
  10       print $record->title(),"\n";
  11   }
  12
  13   ## make sure there weren't any problems.
  14   if ( my @warnings = $batch->warnings() ) {
  15       print "\nWarnings were detected!\n", @warnings;
  16   }

The call to C<warnings()> at line 14 will retrieve any warning messages and store
them in C<@warnings>. This allows you to detect when C<next()> has aborted
prematurely (before the end of the file has been reached). When a warning is
detected, an explanation is sent to C<STDERR>. By introducing an error into
'camel.usmarc', we'll receive the following output to C<STDOUT>:

  Warnings were detected!
  Invalid indicators "a0" forced to blanks in record 1 for tag 245

=head2 Recovering from errors

You may want to keep reading a batch file even after an error has been encountered.
If so, you will want to turn strict mode off using the C<strict_off()> method. You
can also prevent warnings from being printed to C<STDERR> using the C<warnings_off()>
method. By default, strict is on as a safety precaution to prevent you from using corrupt
MARC data.  Once off, you can turn both strict and warnings back on again with the
C<strict_on()> and C<warnings_on()> methods.

   1   ## Example R4
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC', 'file.dat');
   5   $batch->strict_off();
   6
   7   while ( my $record = $batch->next() ) {
   8      print $record->title(),"\n";
   9   }
  10
  11   ## make sure there weren't any problems.
  12   if ( my @warnings = $batch->warnings() ) {
  13       print "\nWarnings were detected!\n", @warnings;
  14   }

Introducing a second error to the 'camel.usmarc' file gives the following:

   ActivePerl with ASP and ADO / Tobias Martinsson.
   Programming the Perl DBI / Alligator Descartes and Tim Bunce.
   .
   .
   .
   Cross-platform Perl / Eric F. Johnson.

   Warnings were detected!
   Invalid indicators "a0" forced to blanks in record 1 for tag 245
   Invalid indicators "a0" forced to blanks in record 5 for tag 245

=head2 Looking at a field

Our previous examples use MARC::Record's C<title()> method to easily access
the 245 field, but you will probably want programs that access lots of other
MARC fields. MARC::Record's C<field()> method gives you complete access to the
data found in any MARC field. The C<field()> method returns a MARC::Field
object which can be used to access the data, indicators, and even the
individual subfields. Our next example shows how this is done.

   1   ## Example R5
   2
   3   ## open a file.
   4   use MARC::Batch;
   5   my $batch = MARC::Batch->new('USMARC','file.dat');
   6
   7   ## read a record.
   8   my $record = $batch->next();
   9
  10   ## get the 100 field as a MARC::Field object.
  11   my $field = $record->field('100');
  12   print "The 100 field contains: ",$field->as_string(),"\n";
  13   print "The 1st indicator is ",$field->indicator(1),"\n";
  14   print "The 2nd indicator is ",$field->indicator(2),"\n";
  15   print "Subfield d contains: ",$field->subfield('d'),"\n";

Which results in something like:

  The 100 field contains: Martinsson, Tobias, 1976-
  The 1st indicator is 1
  The 2nd indicator is
  Subfield d contains: 1976-

As before, use a C<while> loop to iterate through all the records in a batch.

=head2 Looking at repeatable fields

So how do you retrieve data from repeatable fields? The C<field()> method
can help you with this as well.  In our previous example's line 11, the
C<field()> method was used in a I<scalar> context, since the result was being
assigned to the variable C<$field>. However in a I<list> context, C<field()>
will return all the fields in the record of that particular type. For example:

   1   ## Example R6
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   my $record = $batch->next();
   6
   7   ## get all the 650 fields (list context).
   8   my @fields = $record->field('650');
   9
  10   ## examine each 650 field and print it out.
  11   foreach my $field (@fields) {
  12     print $field->as_string(),"\n";
  13   }

Which prints out the following for the first record of 't/camel.usmarc':

  Active server pages.
  ActiveX.

=head2 Looking at a set of related fields

C<field()> also allows you to retrieve similar fields using '.' as a wildcard.

   1   ## Example R7
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   my $record = $batch->next();
   6
   7   # retrieve all title fields in one shot.
   8   foreach my $field ($record->field('2..')) {
   9     print $field->tag(),' contains ',$field->as_string(),"\n";
  10   }

Notice the shorthand in line 8 which compacts lines 7-13 of our previous example.
Instead of storing the fields in an array, the C<field()> still returns a list
in the C<for> loop. Line 9 uses the C<tag()> method which returns the tag number
for a particular MARC field, which is useful when you aren't certain what
tag you are currently dealing with. Sample output from this recipe:

   245 contains ActivePerl with ASP and ADO / Tobias Martinsson.
   260 contains New York : John Wiley & Sons, 2000.

You  can also return all tags for a specific record by using '...'
in C<field> (though, see the next recipe).

=head2 Looking at all the fields in a record

The last example in this section illustrates how to retrieve I<all> the fields
in a record using the C<fields()> method. This method is similar to passing
'...' as a wildcard (see our previous recipe for alternative access).

   1   ## Example R8
   2
   3   use MARC::Batch;
   4   my $file = MARC::Batch->new('USMARC','file.dat');
   5   my $record = $batch->next();
   6
   7   ## get all of the fields using the fields() method.
   8   my @fields = $record->fields();
   9
  10   ## print out the tag, the indicators and the field contents.
  11   foreach my $field (@fields) {
  12     print
  13       $field->tag(), " ",
  14       defined $field->indicator(1) ? $field->indicator(1) : "",
  15       defined $field->indicator(2) ? $field->indicator(2) : "",
  16       " ", $field->as_string, " \n";
  17   }

The above code would print the following for the first record of 't/camel.usmarc':

  001  fol05731351
  003  IMchF
  .
  .
  .
  300    xxi, 289 p. : ill. ; 23 cm. + 1 computer  laser disc (4 3/4 in.)
  500    "Wiley Computer Publishing."
  650  0 Perl (Computer program language)
  630 00 Active server pages.
  630 00 ActiveX.



=head1 CREATING

The examples in the Section 1 covered how to read in existing USMARC data
in a file. Section 2 will show you how to create a MARC record from scratch.
The techniques in this section would allow you to write programs which
create MARC records that could then be loaded into an online catalog, or
sent to a third party.

=head2 Creating a record

To create a new MARC record, you'll need to first create a MARC::Record object,
add a leader (though MARC::Record can create leaders automatically if you don't
specifically define one), and then create and add MARC::Field objects to your
MARC::Record object. For example:

   1   ## Example C1
   2
   3   ## create a MARC::Record object.
   4   use MARC::Record;
   5   my $record = MARC::Record->new();
   6
   7   ## add the leader to the record. optional.
   8   $record->leader('00903pam  2200265 a 4500');
   9
  10   ## create an author field.
  11   my $author = MARC::Field->new(
  12     '100',1,'',
  13       a => 'Logan, Robert K.',
  14       d => '1939-'
  15     );
  16   $record->append_fields($author);
  17
  18   ## create a title field.
  19   my $title = MARC::Field->new(
  20     '245','1','4',
  21       a => 'The alphabet effect /',
  22       c => 'Robert K. Logan.'
  23     );
  24   $record->append_fields($title);

The key to creating records from scratch is to use C<append_fields()>, which adds
a field to the end of the record. Since each field gets added at the end, it's up
to you to order the fields the way you want. C<insert_fields_before()> and
C<insert_fields_after()> are similar methods that allow you to define where
the field gets added. These methods are covered in more detail below.



=head1 WRITING

Sections 1 and 2 showed how to read and create USMARC data. Once you know how
to read and create, it becomes important to know how to write the USMARC data
to disk in order to save your work. In these examples, we will create a new record
and save it to a file called 'record.dat'.

=head2 Writing records to a file

   1   ## Example W1
   2
   3   ## create a MARC::Record object.
   4   use MARC::Record;
   5   my $record = MARC::Record->new();
   6
   7   ## add the leader to the record. optional.
   8   $record->leader('00903pam  2200265 a 4500');
   9
  10   ## create an author field.
  11   my $author = MARC::Field->new(
  12     '100',1,'',
  13       a => 'Logan, Robert K.',
  14       d => '1939-'
  15     );
  16
  17   ## create a title field.
  18   my $title = MARC::Field->new(
  19     '245','1','4',
  20       a => 'The alphabet effect /',
  21       c => 'Robert K. Logan.'
  22     );
  23
  24   $record->append_fields($author, $title);
  25
  26   ## open a filehandle to write to 'record.dat'.
  27   open(OUTPUT, '> record.dat') or die $!;
  28   print OUTPUT $record->as_usmarc();
  29   close(OUTPUT);


The C<as_usmarc()> method call at line 28 returns a scalar value which is
the raw USMARC data for C<$record>. The raw data is then promptly printed to
the C<OUTPUT> file handle. If you want to output multiple records to a file,
simply repeat the process at line 28 for the additional records. Also of
note is the C<append_fields> method: unlike recipe C1 which called the
method once for each field added, this recipe demonstrates that
C<append_fields> can accept multiple arguments.

Note to the curious: the C<as_usmarc()> method is actually an alias to the
MARC::File::USMARC C<encode()> method. Having separate C<encode()> methods is
a design feature of the MARC class hierarchy, since it allows extensions to
be built that translate MARC::Record objects into different data formats.

=head2 Debugging with C<as_formatted()>

Since raw USMARC data isn't very easy for humans to read, it is often useful
to be able to see the contents of your MARC::Record object represented in a
'pretty' way for debugging purposes. If you have a MARC::Record object you'd
like to pretty-print, use the C<as_formatted()> method.

   1   ## Example W2
   2
   3   ## create a MARC::Record object.
   4   use MARC::Record;
   5   my $record = MARC::Record->new();
   6
   7   $record->leader('00903pam  2200265 a 4500');
   8
   9   $record->append_fields(
  10    MARC::Field->new('100','1','', a=>'Logan, Robert K.', d=>'1939-'),
  11    MARC::Field->new('245','1','4', a=>'The alphabet effect /', c=>'Robert K. Logan.')
  12   );
  13
  14   ## pretty print the record.
  15   print $record->as_formatted(), "\n";

This code will pretty print the contents of the newly created record:

  LDR 00903pam  2200265 a 4500
  100 1  _aLogan, Robert K.
         _d1939-
  245 14 _aThe alphabet effect /
         _cRobert K. Logan.

Notice on lines 9-12 how you can add a list of new fields by creating
MARC::Field objects within a call to C<append_fields()>. This is yet
another shorthand method to those shown in recipes C1 and W1. For more
pretty-printing capabilities, try C<marcdump()> in our next recipe.

=head2 Debugging with marcdump()

If you have written USMARC data to a file (as in recipe W2) and you would
like to verify that the data is stored correctly you can use the C<marcdump>
command line utility that was installed with the MARC::Record package:

 % marcdump record.dat
 record.dat
 LDR 00122pam  2200049 a 4500
 100 1  _aLogan, Robert K.
        _d1939-
 245 14 _aThe alphabet effect /
        _cRobert K. Logan.

  Recs  Errs Filename
 ----- ----- --------
     1     0 record.dat

As you can see, this command results in the record being pretty printed to
your screen (C<STDOUT>) similarly to the C<as_formatted> method from recipe
W2. It is useful for verifying your USMARC data after it has been stored on
disk. More details about debugging are found later in VALIDATING.



=head1 UPDATING

Now that you know how to read, write and create MARC data, you have the
tools you need to update or edit exiting MARC data. Updating MARC
data is a common task for library catalogers. Sometimes there are huge
amounts of records that need to be touched up... and while the touch ups are
very detail oriented, they are also highly repetitive. Luckily, computers
are tireless, and not very prone to error (assuming the programmer isn't).

When libraries receive large batches of MARC records for electronic text
collections such as NetLibrary, Making of America, or microfiche sets like
Early American Imprints, the records are often loaded into an online system
and then the system is used to update the records. Unfortunately, not all
these systems are created equal, and catalogers have to spend a great deal
of time touching up each individual record. An alternative would be to
process the records prior to import and then, once in the system, the records
would not need editing. This scenario would save a great deal of time for
the cataloger who would be liberated to spend their time doing original
cataloging... which computers are notably bad at!

=head2 Adding a field

Imagine a batch of records in 'file.dat' that you'd like to add local notes (590)
to, then saving your changes:

   1   ## Example U1
   2
   3   ## create our MARC::Batch object.
   4   use MARC::Batch;
   5   my $batch = MARC::Batch->new('USMARC','file.dat');
   6
   7   ## open a file handle to write to.
   8   open(OUT,'>new.dat') or die $!;
   9
  10   ## read each record, modify, then print.
  11   while ( my $record = $batch->next() ) {
  12
  13       ## add a 590 field.
  14       $record->append_fields(
  15          MARC::Field->new('590','','',a=>'Access provided by Enron.')
  16       );
  17
  18       print OUT $record->as_usmarc();
  19
  20   }
  21
  22   close(OUT);

=head2 Preserving field order

As its name suggests, C<append_fields()> will add the 590 field in recipe U1
to the end of the record. If you want to preserve a particular order, you can
use the C<insert_fields_before()> and C<insert_fields_after()> methods. In order
to use these, you need to locate the field you want to insert before or after.
Here is an example (C<insert_fields_after()> works similarly):

   1   ## Example U2
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   open(OUT,'>new.dat') or die $!;
   6
   7   ## read in each record.
   8   while ( my $record = $batch->next() ) {
   9
  10       ## find the tag after 590.
  11       my $before;
  12       foreach ($record->fields()) {
  13           $before = $_;
  14           last if $_->tag() > 590;
  15       }
  16
  17       ## create the 590 field.
  18       my $new = MARC::Field->new('590','','',a=>'Access provided by Enron.');
  19
  20       ## insert our 590 field after the $before.
  21       $record->insert_fields_before($before,$new);
  22
  23       ## and print out the new record.
  24       print OUT $record->as_usmarc();
  25
  26   }

=head2 Deleting a field

You can also delete fields that you don't want. But you will probably want
to check that the field contains what you expect before deleting it. Let's
say Enron has gone out of business and the 590 field needs to be deleted:

   1   ## Example U3
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','new.dat');
   5   open(OUT,'>newer.dat') or die $1;
   6
   7   while ( my $record = $batch->next() ) {
   8
   9     ## get the 590 record.
  10     my $field = $record->field('590');
  11
  12     ## if there is a 590 AND it has the word "Enron"...
  13     if ($field and $field->as_string() =~ /Enron/i) {
  14
  15       ## delete it!
  16       $record->delete_field($field);
  17
  18     }
  19
  20     ## output possibly modified record.
  21     print OUT $record->as_usmarc();
  22
  23   }

The 590 field is retrieved on line 10, but notice how we check that we
actually received a valid C<$field>, and that it then contains the word
'Enron' before we delete it. You need to pass C<delete_field()> a MARC::Field
object that can be retrieved with the C<field()> method.

=head2 Changing existing fields

Perhaps rather than adding or deleting a field, you need to modify an
existing field. This is achieved in several steps: first, read in the
MARC record you want to update, and then the field you're interested in.
From there, call the field's C<update> or C<replace_with> methods to modify
its contents, and then resave the record. Below is an example of updating existing
590 field's containing the word 'Enron' to indicate that access is now
provided through Arthur Andersen:

   1   ## Example U4
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','new.dat');
   5   open(OUT,'>newer.dat') or die $1;
   6
   7   while ( my $record = $batch->next() ) {
   8
   9     ## look for a 590 containing "Enron"...
  10     my $field = $record->field('590');
  11     if ($field and $field->as_string =~ /Enron/i) {
  12
  13       ## create a new 590 field.
  14       my $new_field = MARC::Field->new(
  15         '590','','', a => 'Access provided by Arthur Andersen.' );
  16
  17       ## replace existing with our new one.
  18       $field->replace_with($new_field);
  19
  20     }
  21
  22     ## output possibly modified record.
  23     print OUT $record->as_usmarc();
  24
  25   }

In this example, we used MARC::Field's method C<replace_with()> to replace
an existing field in the record with a new field that we created. To use
C<replace_with()>, you need to retrieve the field you want to replace from
a MARC::Record object (line 10), create a new field to replace the existing
one with (lines 13-15), and then call the existing field's C<replace_with()>
method passing the new field as an argument (lines 18). You must pass
C<replace_with()> a valid MARC::Field object.

=head2 Updating subfields and indicators

If you'd rather not replace an existing field with a new one, you can also
edit the contents of the field itself using the C<update()> method. Let's say
you've got a batch of records and want to make sure that the 2nd indicator
for the 245 field is properly set for titles that begin with 'The' (where
the indicator should be '4').

   1   ## Example U5
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   open(OUT,'>new.dat') or die $!;
   6
   7   while (my $record = $batch->next()) {
   8
   9     ## retrieve the 245 record.
  10     my $field_245 = $record->field('245');
  11
  12     ## if we got 245 and it starts with 'The'...
  13     if ($field_245 and $field_245->as_string() =~ /^The /) {
  14
  15       ## if the 2nd indicator isn't 4, update
  16       if ($field_245->indicator(2) != 4) {
  17         $field_245->update( ind2 => 4 );
  18       }
  19
  20     }
  21
  22     print OUT $record->as_usmarc();
  23
  24   }

In a similar fashion, you can update individual or multiple subfields:

  $field_245->update( a => 'History of the World :', b => 'part 1' );

But beware, you can only update the first occurrence of a subfield using
C<update()>. If you need to do more finer grained updates, you are advised to
build a new field and replace the existing field with C<replace_with()>.

=head2 Changing a record's leader

The above procedure works for fields, but editing the leader requires that you
use the C<leader()> method. When called with no arguments, C<leader()> will return
the current leader, and when you pass a scalar value as an argument, the
leader will be set to this value. This example shows how you might want
to update position 6 of a records leader to reflect a computer file.

   1   ## Example U6
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   open(OUT,'>new.dat') or die $!;
   6   my $record = $batch->next();
   7
   8   ## get the current leader.
   9   my $leader = $record->leader();
  10
  11   ## replace position 6 with 'm'
  12   substr($leader,6,1) = 'm';
  13
  14   ## update the leader
  15   $record->leader($leader);
  16
  17   ## save the record to a file
  18   print OUT $record->as_usmarc();

=head2 Modifying fields without indicators

MARC::Record and MARC::Field are smart and know that you don't have field
indicators with tags less than 010. Here's an example of updating/adding
an 005 field to indicate a new transaction time. For a little pizzazz, we
use Perl's C<localtime()> to generate the data we need for this field.

   1   ## Example U7
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','file.dat');
   5   open(OUT,'>new.dat') or die $!;
   6
   7   while (my $record = $batch->next() ) {
   8
   9     ## see if there is a 005 field.
  10     my $field_005 = $record->field('005');
  11
  12     ## delete it if we find one.
  13     $record->delete_field($field_005) if $field_005;
  14
  15     ## figure out the contents of our new 005 field.
  16     my ($sec,$min,$hour,$mday,$mon,$year) = localtime();
  17     $year += 1900; $mon += 1; # catering to offsets.
  18     my $datetime = sprintf("%4d%02d%02d%02d%02d%02d.0",
  19                             $year,$mon,$mday,$hour,$min,$sec);
  20
  21     ## create a new 005 field using our new datetime.
  22     $record->append_fields( MARC::Field->new('005',$datetime) );
  23
  24     ## save record to a file.
  25     print OUT $record->as_usmarc();
  26
  27   }

=head2 Reordering subfields

You may find yourself in the situation where you would like to
programmatically reorder, and possibly modify, subfields in a particular
field. For example, imagine that you have a batch of records that have
856 fields which contain subfields z, u, and possibly 3... in any order!
Now imagine that you'd like to standardize the subfield z, and reorder them
so that subfield 3 precedes subfield z, which precedes subfield u. This is
tricky but can be done in the following manner: read in a record, extract
the existing 856 field, build a new 856 field based on the existing one,
replace the existing field with your newly created version.

   1   ## Example U8
   2
   3   use MARC::Batch;
   4   my $batch = MARC::Batch->new('USMARC','856.dat');
   5   open(OUT,'>856_new.dat') or die $!;
   6
   7   while (my $record = $batch->next()) {
   8
   9     my $existing = $record->field('856');
  10
  11     ## make sure 856 exists.
  12     if ($existing) {
  13
  14       ## our ordered subfields.
  15       my @subfields = ();
  16
  17       ## if we have a subfield 3, add it.
  18       if (defined($existing->subfield('3'))) {
  19         push(@subfields,'3',$existing->subfield('3'));
  20       }
  21
  22       ## now add subfields z and u.
  23       push(@subfields,'z','Access restricted',
  24         'u',$existing->subfield('u'));
  25
  26       ## create a new 856.
  27       my $new = MARC::Field->new(
  28          856', $existing->indicator(1),
  29          $existing->indicator(2), @subfields
  30       );
  31
  32       ## replace the existing subfield.
  33       $existing->replace_with($new);
  34
  35     }
  36
  37     ## write out the record
  38     print OUT $record->as_usmarc();
  39
  40   }

=head2 Updating subject subfield x to subfield v

As a somewhat more complicated example, you may find yourself wanting to
update the last subfield x in a 650 field to be a subfield v instead. With
the  MARC::Field C<subfields()> and C<replace_with()> methods along with
some  fancy footwork this can be done relatively easily.

   1  ## Example U9
   2
   3  use MARC::Batch;
   4
   5  my $file = shift;
   6
   7  my $batch = MARC::Batch->new('USMARC', $file);
   8  while ( my $record = $batch->next() ) {
   9
  10    # go through all 6XX fields in the record.
  11    foreach my $subject ( $record->field( '6..' ) ) {
  12
  13      # extract subfields as an array of array refs.
  14      my @subfields = $subject->subfields();
  15
  16      # setup an array to store our new field.
  17      my @newSubfields = ();
  18
  19      # a flag to indicate that we found an subfield x.
  20      my $foundX = 0;
  21
  22      # use pop() to read the subfields backwards.
  23      while ( my $subfield = pop( @subfields ) ) {
  24
  25        # for convenience, pull out the subfield
  26        # code and data from  the array ref.
  27        my ($code,$data) = @$subfield;
  28
  29        # if the subfield code is 'x' and
  30        # we haven't already found one...
  31        if ( $code eq 'x' and ! $foundX ) {
  32
  33          # change to a v.
  34          $code = 'v';
  35
  36          # set flag so we know not to
  37          # translate any more subfield x.
  38          $foundX = 1;
  39
  40        }
  41
  42        # add our (potentially changed) subfield
  43        # data to our new subfield data array.
  44        unshift( @newSubfields, $code, $data );
  45
  46      }
  47
  48      # if we did find a subfield x, then create a new field using our
  49      # new subfield data, and replace the old one with the new one.
  50      if ( $foundX ) {
  51        my $newSubject = MARC::Field->new(
  52          $subject->tag(),
  53          $subject->indicator(1),
  54          $subject->indicator(2),
  55          @newSubfields
  56        );
  57        $subject->replace_with( $newSubject );
  58      }
  59
  60    }
  61
  62    # output the potentially changed record as MARC.
  63    print $record->as_usmarc();
  64
  65  }



=head1 VALIDATING

MARC::Lint, available on CPAN and in cvs on SourceForge, has some extra goodies
to allow you to validate records. MARC::Lint provides an extensive battery of
tests, and it also provides a framework for adding more.

=head2 Using MARC::Lint

Here is an example of using MARC::Lint to generate a list of errors
present in a batch of records in a file named 'file.dat':

   1   ## Example V1
   2
   3   use MARC::Batch;
   4   use MARC::Lint;
   5
   6   my $batch = MARC::Batch->new('USMARC','file.dat');
   7   my $linter = MARC::Lint->new();
   8   my $counter = 0;
   9
  10   while (my $record = $batch->next() ) {
  11
  12     $counter++;
  13
  14     ## feed the record to our linter object.
  15     $linter->check_record($record);
  16
  17     ## get the warnings...
  18     my @warnings = $linter->warnings();
  19
  20     ## output any warnings.
  21     if (@warnings) {
  22
  23       print "RECORD $counter\n";
  24       print join("\n",@warnings),"\n";
  25
  26     }
  27
  28   }

MARC::Lint is quite thorough, and will check the following when validating:
presence of a 245 field, repeatability of fields and subfields, valid use of
subfield within particular fields, presence of indicators and their values. All
checks are based on MARC21 bibliographic format.

=head2 Customizing MARC::Lint

MARC::Lint makes no claim to check B<everything> that might be wrong with
a MARC record. In practice, individual libraries may have their own idea
about what is valid or invalid. For example, a library may mandate that
all MARC records with an 856 field should have a subfield z that reads
"Connect to this resource".

MARC::Lint does provide a framework for adding rules. It can be done using
the object oriented programming technique of inheritance. In short, you
can create your own subclass of MARC::Lint, and then use it to validate your
records. Here's an example:

   1   ## Example V2
   2
   3   ## first, create our own subclass of MARC::Lint.
   4   ## should be saved in a file called MyLint.pm.
   5
   6   package MyLint;
   7   use base qw(MARC::Lint);
   8
   9   ## add a method to check that the 856
  10   ## fields contain a correct subfield z.
  11   sub check_856 {
  12
  13     ## your method is passed the MARC::Lint
  14     ## and MARC::Field objects for the record.
  15     my ($self,$field) = @_;
  16
  17     if ($field->subfield('z') ne 'Connect to this resource') {
  18
  19       ## add a warning to our lint object.
  20       $self->warn("856 subfield z must read 'Connect to this resource'.");
  21
  22     }
  23
  24   }

Then create a separate program that uses your subclass to validate your MARC
records. You'll need to make sure your program is able to find your module
(in this case, MyLint.pm)... this can be achieved by putting both MyLint.pm
and the following program in the same directory:

   1   ## Example V3
   2
   3   use MARC::Batch;
   4   use MyLint;
   5
   6   my $linter = MyLint->new();
   7   my $batch = MARC::Batch->new('USMARC','file.marc');
   8   my $counter = 0;
   9
  10   while (my $record = $batch->next()) {
  11
  12     $counter++;
  13
  14     ## check the record
  15     $linter->check_record($record);
  16
  17     ## get the warnings, and print them out
  18     my @warnings = $linter->warnings();
  19     if (@warnings) {
  20       print "RECORD $counter\n";
  21       print join("\n",@warnings),"\n";
  22     }
  23
  24   }

Notice how the call to C<check_record()>  at line 15 automatically calls the
C<check_record> in MARC::Lint. The property of inheritance is what makes
this happen. C<$linter> is an instance of the MyLint class, and MyLint
inherits from the MARC::Lint class, which allows C<$linter> to inherit all
the functionality of a normal MARC::Lint object B<plus> the new
functionality found in the C<check_856> method.

Notice also that we don't have to call C<check_856()> directly. The call to
C<check_record()> automatically looks for any C<check_XXX> methods that it can
call to verify the record. Pretty neat stuff. If you've added validation
checks that you think could be of use to the general public, please share them
on the perl4lib mailing list, or become a developer and add them to the source!

=head1 SWOLLEN APPENDICES

Brian Eno fans might catch this reference to his autobiography which was
comprised of a years worth of diary entries plus extra topics at the end, and
was entitled "A Year With Swollen Appendices". The following section is a grab
bag group of appendices. Many of them are not filled in yet; this is because
they are just ideas... so perhaps the appendices aren't that swollen yet.
Feel free to suggest new ones, or to fill these in.

=head2 Comparing Collections

=head2 Authority Records

=head2 URLs

=head2 ISBN/ISSNs

=head2 Call numbers

=head2 Subject headings

Suppose you have a batch of MARC records and you want to extract all the
subject headings, generating a report of how many times each subject
heading appeared in the batch:

   1   use MARC::File::USMARC;
   2   use constant MAX => 20;
   3
   4   my %counts;
   5
   6   my $filename = shift or die "Must specify filename\n";
   7   my $file = MARC::File::USMARC->in( $filename );
   8
   9   while ( my $marc = $file->next() ) {
  10       for my $field ( $marc->field("6..") ) {
  11           my $heading = $field->subfield('a');
  12
  13           # trailing whitespace / punctuation.
  14           $heading =~ s/[.,]?\s*$//;
  15
  16           # Now count it.
  17           ++$counts{$heading};
  18       }
  19   }
  20   $file->close();
  21
  22   # Sort the list of headings based on the count of each.
  23   my @headings = reverse sort { $counts{$a} <=> $counts{$b} } keys %counts;
  24
  25   # Take the top N hits...
  26   @headings = @headings[0..MAX-1];
  27
  28   # And print out the results.
  29   for my $heading ( @headings ) {
  30       printf( "%5d %s\n", $counts{$heading}, $heading );
  31   }

Which will generate results like this:

  600 United States
  140 World War, 1939-1945
   78 Great Britain
   63 Afro-Americans
   61 Indians of North America
   58 American poetry
   55 France
   53 West (U.S.)
   53 Science fiction
   53 American literature
   50 Shakespeare, William
   48 Soviet Union
   46 Mystery and detective stories
   45 Presidents
   43 China
   40 Frontier and pioneer life
   38 English poetry
   37 Authors, American
   37 English language
   35 Japan

=head2 HTML

=head2 XML

=head2 MARCMaker

MARC::File::MARCMaker, available on CPAN and in cvs on SourceForge, is a
subclass of MARC::File for working with MARC 21 data encoded in the format used
by the Library of Congress MARCMaker and MARCBreaker programs
(L<http://www.loc.gov/marc/makrbrkr.html>) and MarcEdit ().

An example of a brief record in this format:

 =LDR  00314nam  22001215a 4500
 =001  ctr00000123\
 =003  XX-XxUND
 =005  20000613133448.0
 =008  051029s2005\\\\xxua\\\\\\\\\\001\0\eng\\
 =040  \\$aXX-XxUND$cXX-XxUND
 =245  00$aSample of MARCMaker record.
 =260  \\$a[United States] :$b[S.n.],$c2005.
 =300  \\$a1 p. ;$c28 cm.

The following example converts an ISO2709 format record into MARCMaker format.

   1    ## Example Maker1
   2
   3    use MARC::Batch;
   4    use MARC::File::MARCMaker;
   5
   6    #mrc indicates ISO2709 format
   7    my $mrc_in = 'in.mrc';
   8    #mrk indicates MARCMaker format
   9    my $mrk_out = 'out.mrk';
   10
   11   #initialize $batch_mrc as new MARC::Batch object
   12   my $batch_mrc = MARC::Batch->new('USMARC', $mrc_in);
   13
   14   #open mrk (MARCMaker) format output file
   15   open (OUTMRK, ">$mrk_out") || die "Cannot open $mrk_out, $!";
   16
   17   my $rec_count = 0;
   18   while (my $record = $batch_mrc->next()) {
   19      $rec_count++;
   20
   21      print OUTMRK MARC::File::MARCMaker->encode($record);
   22
   23   } # while
   24
   25   print "$rec_count records processed\n";

The following example shows conversion from MARCMaker format to ISO2709 format.

   1    ## Example Maker2
   2
   3    use MARC::Batch;
   4    use MARC::File::MARCMaker;
   5
   6    #mrk indicates MARCMaker format
   7    my $mrk_in = 'in.mrk';
   8    #mrc indicates ISO2709 format
   9    my $mrc_out = 'out.mrc';
   10
   11   #initialize $batch_mrk as new MARC::Batch object
   12   my $batch_mrk = MARC::Batch->new( 'MARCMaker', $mrk_in);
   13
   14   #open mrc (ISO2709) format output file
   15   open (OUTMRC, ">$mrc_out") || die "Cannot open $mrc_out, $!";
   16
   17   my $rec_count = 0;
   18   while (my $record = $batch_mrk->next()) {
   19      $rec_count++;
   20
   21      print OUTMRC $record->as_usmarc();
   22
   23   } # while
   24
   25   print "$rec_count records processed\n";

=head2 Excel

=head2 Z39.50

Chris Biemesderfer was kind enough to contribute a short example of how
to use MARC::Record in tandem with Net::Z3950.  Net::Z3950 is a CPAN
module which provides an easy to use interface to the Z39.50 protocol so that
you can write programs that retrieve records from bibliographic database
around the world.

Chris' program is a command line utility which you run like so:

  ./zm.pl 0596000278

where 0596000278 is an ISBN (for the 3rd edition of the Camel incidentally).
The program will query the Library of Congress Z39.50 server for the ISBN,
and dump out the retrieved MARC record on the screen. The program is designed
to lookup multiple ISBNs if you separate them with a space.  This is just an
example showing what is possible.

   1   #!/usr/bin/perl -w
   2
   3   # GET-MARC-ISBN -- Get MARC records by ISBN from a Z39.50 server
   4
   5   use strict;
   6   use Carp;
   7   use Net::Z3950;
   8   use MARC::Record;
   9
  10   exit if ($#ARGV < 0);
  11
  12   # We handle multiple ISBNs in the same query by assembling a
  13   # (potentially very large) search string with Prefix Query Notation
  14   # that ORs the ISBN-bearing attributes.
  15   #
  16   # For purposes of automation, we want to request batches of many MARC
  17   # records.  I am not a Z39.50 weenie, though, and I don't know
  18   # offhand if there is a limit on how big a PQN query can be...
  19
  20   my $zq = "\@attr 1=7 ". pop();
  21   while (@ARGV) { $zq = '@or @attr 1=7 '. pop() ." $zq" }
  22
  23   ## HERE IS THE CODE FOR Z3950 REC RETRIEVAL
  24   # Set up connection management structures, connect
  25   # to the server, and submit the Z39.50 query.
  26
  27   my $mgr = Net::Z3950::Manager->new( databaseName => 'voyager' );
  28   $mgr->option( elementSetName => "f" );
  29   $mgr->option( preferredRecordSyntax => Net::Z3950::RecordSyntax::USMARC );
  30
  31   my $conn = $mgr->connect('z3950.loc.gov', '7090');
  32   croak "Unable to connect to server" if !defined($conn);
  33
  34   my $rs = $conn->search($zq);
  35
  36   my $numrec = $rs->size();
  37   print STDERR "$numrec record(s) found\n";
  38
  39   for (my $ii = 1; $ii <= $numrec; $ii++) {
  40
  41       # Extract MARC records from Z3950
  42       # result set, and load MARC::Record.
  43       my $zrec = $rs->record($ii);
  44       my $mrec = MARC::Record->new_from_usmarc($zrec->rawdata());
  45       print $mrec->as_formatted, "\n\n";
  46
  47   }

=head2 Databases

Here's a script that will do a Z39.50 query (using Chris Biemesderfer's zm.pl
as a model), get a MARC record back, and store it as a binary blob in a MySQL
table of this structure:

 +---------------+---------------+------+-----+---------+----------------+
 | Field         | Type          | Null | Key | Default | Extra          |
 +---------------+---------------+------+-----+---------+----------------+
 | TitleID       | int(7)        |      | PRI | NULL    | auto_increment |
 | RecLastMod    | timestamp(14) | YES  |     | NULL    |                |
 | ISSN          | text          | YES  |     | NULL    |                |
 | RawMARCRecord | blob          | YES  |     | NULL    |                |
 +---------------+---------------+------+-----+---------+----------------+

   1 #!/usr/bin/perl -w
   2
   3 # Script that reads in a file of ISSNs, queries a Z39.50 server,
   4 # and stores resulting records in a database. Limitations: Only
   5 # stores 1 records per ISSN.
   6 # Last updated 2004-09-08 Mark Jordan, mjordan@sfu.ca
   7
   8 use strict;
   9 use Carp;
  10 use Net::Z3950;
  11 use MARC::Record;
  12 use DBI;
  13
  14 # DB connection settings
  15 my $host = "somehost";
  16 my $user = "someuser";
  17 my $password = "somepass";
  18 my $database = "somedb";
  19
  20 # Input file (one ISSS/line)
  21 my $InputFile = $ARGV[0];
  22
  23 # Prepare list of ISSNs to search
  24 my @ISSNs;
  25 open (INPUT, "< $InputFile") or die "Can't find input file\n";
  26 while (<INPUT>) { chomp $_; push (@ISSNs, $_); }
  27 close INPUT;
  28
  29
  30 # Set up connection management structures, connect to the server,
  31 # and submit the Z39.50 query.
  32 my $mgr = Net::Z3950::Manager->new( databaseName => 'voyager' );
  33 $mgr->option( elementSetName => "f" );
  34 $mgr->option( preferredRecordSyntax => Net::Z3950::RecordSyntax::USMARC );
  35 my $conn = $mgr->connect('z3950.loc.gov', '7090');
  36 croak "Unable to connect to server" if !defined($conn);
  37
  38
  39 my $handle = DBI->connect("DBI:mysql:$database:$host","$user","$password")
  40         or die $DBI::errstr;
  41
  42 foreach my $ISSN (@ISSNs) {
  43         my $zq = "\@attr 1=8 ". $ISSN;
  44         my $rs = $conn->search($zq);
  45         my $numrec = $rs->size();
  46         if ($numrec == 0) {
  47             print "Record for ISSN $ISSN not found, moving to next ISSN...\n";
  48             next;
  49         } else {
  50            # Extract MARC record from the result set, and invoke MARC::Record
  51            my $zrec = $rs->record(1);
  52            my $mrec = MARC::Record->new_from_usmarc($zrec->rawdata());
  53            my $rawdata = $zrec->rawdata();
  54            $rawdata = $handle->quote ($rawdata);
  55            # Add to db
  56            my $SQL = "insert into Titles values (NULL,NULL,'$ISSN',$rawdata)";
  57            my $cursor = $handle->prepare($SQL);
  58            $cursor->execute;
  59            print "Record for ISSN $ISSN added to database...\n";
  60            $cursor->finish;
  61         }
  62 }
  63 $handle->disconnect;
  64
  65 __END__

If you want to pull records out of the same database and do something with them,
here's a template script:

   1 #!/usr/bin/perl -w
   2
   3 # Script that gets MARC records (in blobs) from a database.
   4 # Last updated 2004-09-08 Mark Jordan, mjordan@sfu.ca
   5
   6 use strict;
   7 use MARC::Record;
   8 use DBI;
   9
  10 # DB connection settings
  11 my $mysql_host = "somehost";
  12 my $mysql_user = "someuser";
  13 my $mysql_password = "somepass*";
  14 my $mysql_database = "somedb";
  15
  16
  17 my $handle = DBI->connect("DBI:mysql:$mysql_database:$mysql_host",
  18         "$mysql_user","$mysql_password") or die $DBI::errstr;
  19
  20 my $SQL = "select * from Titles";
  21 my $cursor = $handle->prepare($SQL);
  22 $cursor->execute;
  23
  24 while (my @Records = $cursor->fetchrow_array) {
  25         my $RawMARC = $Records[3];
  26         my $mrec = MARC::Record->new_from_usmarc($RawMARC);
  27         # Print out the title
  28         print $mrec->title , "\n";
  29 }
  30
  31 $cursor->finish;
  32 $handle->disconnect;
  33
  34 __END__

=head2 Procite/Endnote

=head1 CONTRIBUTORS

Many thanks to all the contributors who have made this document possible.

=over 4

=item *

Bryan Baldus <eijabb@cpan.org>

=item *

Chris Biemesderfer <chris@seagoat.com>

=item *

Morbus Iff <morbus@disobey.com>

=item *

Mark Jordan <mjordan@sfu.ca>

=item *

Andy Lester <andy@petdance.com>

=item *

Christopher Morgan <morgan@acm.org>

=item *

Shashi Pinheiro <SPinheiro@utsa.edu>

=item *

Jackie Shieh <jshieh@umich.edu>

=item *

Ed Summers <ehs@pobox.com>

=back