convert file from command-line argument
[webpac2] / scripts / mab2marc.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use autodie;
5 use MARC::Record;
6 use Encode;
7 use Data::Dump qw(dump);
8
9 my $source = shift @ARGV || die "usage: $0 file.m21\n";
10 my $dest = $source;
11 $dest =~ s/\..+/.marc/;
12
13 open(my $m21, '<', $source);
14 open(my $out, '>:encoding(utf-8)', $dest);
15
16 warn "# convert $source => $dest\n";
17
18 my $last_id;
19 my @fields;
20 my $marc;
21
22 sub new_marc {
23         $marc = new MARC::Record;
24         $marc->encoding('utf-8');
25         return $marc;
26 }
27
28 $marc = new_marc();
29
30 while (<$m21>) {
31         chomp;
32         my ( $id, $rest ) = split(/\s/, $_, 2);
33         my ( $fffii, $sf ) = split(/\s+L\s+/,$rest,2);
34
35         warn "## ",dump( $id, $fffii, $sf );
36
37         $last_id = $id if ! defined $last_id;
38         if ( $id != $last_id ) {
39                 print $out $marc->as_usmarc;
40                 print "XXX $id\n";
41                 print $marc->as_formatted();
42                 print "\n";
43                 $marc = new_marc();
44                 $last_id = $id;
45         }
46
47         if ( $fffii eq 'LDR' ) {
48                 $sf =~ s/\^/ /g;
49                 $marc->leader( $sf );
50         } elsif ( $fffii =~ m/^00/ ) {
51                 my $field = MARC::Field->new( $fffii, $sf );
52                 $marc->append_fields( $field );
53         } else {
54                 my $f = $1 if $fffii =~ s/^(...)//;
55                 my $i1 = $1 if $fffii =~ s/^(.)//;
56                 my $i2 = $1 if $fffii =~ s/^(.)//;
57                 $i1 ||= ' ';
58                 $i2 ||= ' ';
59
60                 warn "# $id $fffii -> ", dump($f,$i1,$i2), " [$sf]\n";
61
62                 my @f = ( $f, $i1, $i2 );
63
64                 while ( $sf =~ s/^\$\$(\w)([^\$]+)// ) {
65                         push @f, $1, decode('iso-8859-1', $2);
66                 }
67                 warn "### ",dump( @f );
68                 my $field = MARC::Field->new( @f );
69                 $marc->append_fields( $field );
70         }
71 }
72         
73