The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.
#!/usr/bin/perl -w
# vi:et:sw=4 ts=4

=head1 NAME

marcdump - MARC record dump utility

=head1 SYNOPSIS

B<marcdump> [options] file(s)

=cut

use strict;
use integer;

use MARC::File;
use MARC::Record;
use Getopt::Long;

## flag STDOUT for UTF8
binmode( STDOUT, ':utf8' ) if MARC::File::utf8_safe();

my $opt_print = 1;
my $opt_quiet = 0;
my $opt_stats = 1;
my @opt_field = ();
my $opt_help = 0;
my $opt_lif = 0;

my $rc =
    GetOptions(
        "version"   => sub { print "$0, using MARC::Record v$MARC::Record::VERSION\n"; exit 1; },
        "print!"    => \$opt_print,
        "lif!"      => \$opt_lif,
        "quiet!"    => \$opt_quiet,
        "stats!"    => \$opt_stats,
        "field=s"   => \@opt_field,
        "debug!"    => \$MARC::Record::DEBUG,
        "help"      => \$opt_help,
    );

my @files = @ARGV;
if ( $opt_help || !@files || !$rc ) {
    print <DATA>;
    exit 1;
}

my $wants_leader = grep { /LDR/ } @opt_field;

my $class = $opt_lif ? "MARC::File::MicroLIF" : "MARC::File::USMARC";
eval "require $class"; # Must be quoted to get path searching

my %counts;
my %errors;
for my $filename ( @files ) {
    $counts{$filename} = 0;
    $errors{$filename} = 0;

    warn "$filename\n" unless $opt_quiet;

    my $file = $class->in( $filename ) or die $MARC::File::ERROR;

    while ( my $marc = $file->next() ) {
        ++$counts{$filename};
        warn "$counts{$filename} records\n" if ( !$opt_quiet && ($counts{$filename} % 1000 == 0) );

        if ( @opt_field ) {
            $marc = $marc->clone( @opt_field );
            $marc->leader('') unless $wants_leader;
        }

        print $marc->as_formatted, "\n\n" if $opt_print;
        if ( $marc->warnings() ) {
            ++$errors{$filename};
            print join( "\n", $marc->warnings(), "" );
        }
    } # while
    $file->close();
} # for

if ( $opt_stats ) {
    print " Recs  Errs Filename\n";
    print "----- ----- --------\n";
    for my $key ( sort keys %counts ) {
        printf( "%5d %5d %s\n", $counts{$key}, $errors{$key}, $key );
    } # for
} # if stats

__END__
Usage: marcdump [options] file(s)

Options:
    --[no]print     Print a MicroLIF-style dump of each record
    --lif       Input files are MicroLIF, not USMARC
    --field=spec    Specify a field spec to include.  There may be many.
            Examples:
            --field=245 --field=1XX
    --[no]quiet     Print status messages
    --[no]stats     Print a statistical summary by file at the end
    --version       Print version information
    --help      Print this summary