Skip to content

Commit

Permalink
split: raise error for -b 0 (#482)
Browse files Browse the repository at this point in the history
* "perl split -b 0 file" is invalid but did not raise an error due to truth check on $opt{b}
* -b NUMBER has no default value, but it must be >0
* Add explicit checks for options -b, -l and -p which cannot be used together
* test1: "perl split -b 0 file" --> now fails
* test2: "perl split -b 1 file" --> one byte per file
* test3: "perl split -b 5 file" --> final file with <5 bytes (remainder)
* test4: "perl split -l 2 file" --> two lines per file
* test5: "perl split longfile" --> default -l mode: 1000 lines per file
  • Loading branch information
mknos committed Mar 5, 2024
1 parent 62e2a01 commit 0e31314
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions bin/split
Expand Up @@ -97,6 +97,16 @@ exit 1;
#### Main program starts here. ####

getopts('b:l:p:', \my %opt) or clue;
my $nbytes;
if (defined $opt{'b'}) {
$nbytes = get_count($opt{'b'}) or die qq($me: "$opt{b}" is invalid number of bytes\n);
}
my $nlines;
if (defined $opt{'l'}) {
$nlines = get_count($opt{'l'}) or die qq($me: "$opt{l}" is invalid number of lines\n);
}
clue() if ($nbytes && $nlines);
clue() if ($opt{'p'} && ($nbytes || $nlines));

my $infile = shift;
my $prefix = shift;
Expand All @@ -118,14 +128,9 @@ else {
}
binmode $in;
## Byte operations.
if ($opt{b} and (! $opt{p}) and (! $opt{l})) {

if ($opt{'b'}) {
my ($chunk, $fh);
my $count = get_count ($opt{b});

unless ($count) { die qq($me: "$opt{b}" is invalid number of bytes.\n) }

while (read ($in, $chunk, $count) == $count) {
while (read ($in, $chunk, $nbytes) == $nbytes) {
$fh = nextfile ($prefix);
print {$fh} $chunk;
}
Expand All @@ -139,8 +144,7 @@ if ($opt{b} and (! $opt{p}) and (! $opt{l})) {
}

## Split on patterns.
elsif ($opt{p} and (! $opt{b}) and (! $opt{l})) {

elsif ($opt{'p'}) {
my $regex = $opt{p};
my $fh = nextfile ($prefix);

Expand All @@ -151,21 +155,16 @@ elsif ($opt{p} and (! $opt{b}) and (! $opt{l})) {
}

## Line operations.
elsif ((! $opt{p}) and (! $opt{b})) {

# default is -l 1000 (NOT 1k!)
elsif ((! $opt{'p'}) and (! $opt{'b'})) {
my $fh;
my $count = (defined $opt{l} ? get_count($opt{l}) : 1000);
$nlines = 1000 unless $nlines;
my $line = 0;

unless ($count) { die qq($me: "$opt{l}" is invalid number of lines.\n) }

while (<$in>) {
$fh = nextfile ($prefix) if $line % $count == 0;
$fh = nextfile ($prefix) if $line % $nlines == 0;
print {$fh} $_;
$line++;
}

}

else { clue };
Expand Down

0 comments on commit 0e31314

Please sign in to comment.