MARC/Perl
MARC Tutorial
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); |
Preserving field order
As its name suggests, 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 insert_fields_before() andinsert_fields_after() methods. In order to use these, you need to locate the field you want toinsert before or after. Here is an example (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 | } |
