The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

MOP4Import::Base::CLI - Base class for Command Line Interface app.

SYNOPSIS

MyCLI.pm (chmod a+x this!).

  #!/usr/bin/env perl
  package MyCLI;
  use MOP4Import::Base::CLI -as_base, qw/terse_dump/,
      [fields =>
         qw/verbose debug _dbh/,
         [dbname =>
             doc => "filename of sqlite3 database",
             default => "myapp.db"]
      ];
  
  use MOP4Import::Types
    TableInfo => [[fields => qw/
                               TABLE_SCHEM
                               TABLE_NAME
                               TABLE_CAT
                               TABLE_TYPE
                               REMARKS
                             /]];
  
  sub cmd_tables {
    (my MY $self, my ($pattern, $type)) = @_;
    my $sth = $self->DBH->table_info(undef, undef
                                   , $pattern // '%'
                                   , $type // 'TABLE');
    while (my TableInfo $row = $sth->fetchrow_hashref) {
      print $self->{verbose} ? terse_dump($row) : $row->{TABLE_NAME}, "\n";
    }
  }
  
  use DBI;
  sub DBH {
    (my MY $self) = @_;
    $self->{_dbh} //= do {
      DBI->connect("dbi:SQLite:dbname=$self->{dbname}", undef, undef
                 , {PrintError => 0, RaiseError => 1, AutoCommit => 1});
    };
  }
  
  MY->run(\@ARGV) unless caller;
  1;

Then from command line:

  % ./MyCLI.pm
  Usage: MyCLI.pm [--opt-value].. <command> [--opt-value].. ARGS...
  
  Commands:
    help
    tables
  
  Options:
    --verbose
    --debug
    --dbname        filename of sqlite3 database
  % sqlite3 myapp.db "create table foo(x,y)"
  % ./MyCLI.pm tables
  foo
  % ./MyCLI.pm --verbose tables
  {'REMARKS' => undef,'TABLE_NAME' => 'foo','TABLE_SCHEM' => 'main','sqlite_sql' => 'CREATE TABLE foo(x,y)','TABLE_TYPE' => 'TABLE','TABLE_CAT' => undef}
  % 

DESCRIPTION

MOP4Import::Base::CLI is a MOP4Import family and an easy-to-start base class for Command Line Interface applications.

METHODS

run (\@ARGV)

  MY->run(\@ARGV) unless caller;
  1;

This parses minimum posix style options (--name or --name=value) and create your object with them. Then cmd_... entry method of your object will be invoked with first word argument.