diff --git a/bin/unexpand b/bin/unexpand index 7f4116e5..4185f943 100755 --- a/bin/unexpand +++ b/bin/unexpand @@ -27,29 +27,27 @@ License: perl use strict; +use File::Basename qw(basename); + +use constant EX_SUCCESS => 0; +use constant EX_FAILURE => 1; + +my $Program = basename($0); + my $tabstop = 8; my $opt_a = 0; my @tabstops; my @files; -sub usage($;$) -{ - print <<"EOF"; -Usage: -unexpand [-h] [-a] [-tabstop] [-tab1, tab2, ...] [file ...] -EOF - print STDERR $_[1] if $_[1]; - exit $_[0]; -} - -usage(0) if grep {$_ eq "-h"} @ARGV; - my $arg; while($arg = shift @ARGV) { - $opt_a = 1, next if $arg eq "-a"; + if($arg eq '-a') { + $opt_a = 1; + next; + } if($arg =~ /^-(.*)/) { @tabstops = split(/,/, $1); - usage(1) if grep /\D/, @tabstops; + usage() if grep /\D/, @tabstops; next; } push @files, $arg; @@ -58,22 +56,42 @@ while($arg = shift @ARGV) { # $tabstop is used only if multiple tab stops have not been defined $tabstop = $tabstops[0] if scalar @tabstops == 1; -sub is_tab($) -{ +for my $file (@files) { + my $in; + unless (open $in, '<', $file) { + warn "$Program: couldn't open '$file' for reading: $!'\n"; + exit EX_FAILURE; + } + while (<$in>) { + unexpand_line($_); + } + close $in; +} +unless (@files) { + while (<>) { + unexpand_line($_); + } +} +exit EX_SUCCESS; + +sub usage { + warn "usage: $Program [-a] [-tabstop] [-tab1, tab2, ...] [file ...]\n"; + exit EX_FAILURE; +} + +sub is_tab { return (grep {$_ eq $_[0]} @tabstops) if scalar @tabstops >= 2; return ($_[0] % $tabstop == 0); } -sub do_unexpand(@) -{ - for my $line(@_) { - - my $cumul = ""; - my $curs = 0; - my @a = split //, $line; - my $c; - while($c = shift @a) { +sub unexpand_line { + my $line = shift; + my $cumul = ""; + my $curs = 0; + my @a = split //, $line; + my $c; + while($c = shift @a) { if(is_tab($curs)) { if($cumul =~ /^(.*?) +$/) { print "$1\t"; @@ -96,20 +114,8 @@ sub do_unexpand(@) } $cumul .= $c; - } - print $cumul; } -} - -for my $file (@files) { - open IN, '<', $file or usage(1, "couldn't open '$file' for reading: $!'"); - - do_unexpand ; - - close IN; -} -unless (@files) { - do_unexpand ; + print $cumul; } __END__ @@ -120,8 +126,7 @@ unexpand - convert spaces to tabs =head1 SYNOPSIS -unexpand [B<-h>] [B<-a>] [B<-tabstop>] [B<-tab1, tab2, ...>] -[B ...] +unexpand [B<-a>] [B<-tabstop>] [B<-tab1, tab2, ...>] [B ...] =head1 DESCRIPTION @@ -149,10 +154,6 @@ strings of tabs. If the B<-a> option is given, tabs are inserted whenever they would compress the resultant file by replacing two or more characters. -=item -h - -Print a usage message and exit with a status code indicating success. - =back =head1 AUTHOR