On Tue, Feb 14, 2012 at 12:12:07PM -0500, Brandon McCaig wrote:
 
> The program follows (also attached in case my wrapping for mail
> breaks something):

I knew I would forget to attach it. :-X This time hopefully I
remember..

Regards,


-- 
Brandon McCaig <[email protected]> <[email protected]>
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bamccaig.com/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'

#!/usr/bin/perl

use 5.010;
use strict;
use utf8;
use warnings;

use Data::Dumper;
use IO::Handle;
use Getopt::Long qw/GetOptionsFromArray HelpMessage
        :config auto_help bundling no_auto_abbrev no_getopt_compat
        no_ignore_case_always no_require_order permute/;

my $batch_keyword = 'GO';
my $output = 'out.sql';
my $max_size = '10M';

GetOptions(
        'keyword|K=s' => \$batch_keyword,
        'output|O=s' => \$output,
        'max-size|S=s' => \$max_size,
        );

$max_size = parse_stream_size($max_size);

my ($sql_file) = @ARGV;

open my $fh, '< :encoding(utf-8)', $sql_file or die "input: $!";

my $i = 0;

my $buf = '';
my $next_batch = '';

while(my $line = <$fh>)
{
    $next_batch .= $line;
    chomp $line;
    if($line =~ /^\Q$batch_keyword\E$/)
    {
        if(length($buf) + length($next_batch) > $max_size)
        {
            open my $out_fh, '> :encoding(utf-8)',
                    next_file($output, $i++) or die "output: $!";
            $out_fh->print($buf);
            close $out_fh or warn "output: $!";
            $buf = '';
        }
        $buf .= $next_batch;
        $next_batch = '';
    }
}

close $fh or warn "input: $!";

sub next_file
{
    my ($orig, $i) = @_;
    my $format;

    if($orig =~ /\.sql$/)
    {
        ($format = $orig) =~ s/\.sql$/_%04d.sql/;
    }
    else
    {
        $format = $orig . '_%04d';
    }

    return sprintf $format, $i;
}

sub parse_stream_size
{
    my ($size) = @_;
    my ($num, $mult) = $size =~ /((?:[0-9]+)?\.?(?:[0-9]+)?)\s*([BKMG])?/i;

    die "invalid stream size '$size'" unless defined $num && $num > 0;

    my %exp = ('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3);
    my $exp = $exp{uc($mult // 'B')};

    $size = $num * 1024 ** $exp;

    return $size;
}

Attachment: signature.asc
Description: Digital signature

Reply via email to