#!/usr/bin/perl

=begin metadata

Name: rev
Description: reverse lines of a file
Author: Andy Murren, andy@murren.org
License: gpl

=end metadata

=cut

use strict;

use File::Basename qw(basename);
use Getopt::Std qw(getopts);

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my $Program = basename($0);

# unbuffer output to make it look speedier
$|++;

my ($VERSION) = '1.4';

my %opt;
getopts('v', \%opt) or usage();
if ($opt{'v'}) {
	print "$Program $VERSION\n";
	exit EX_SUCCESS;
}

my $rc = EX_SUCCESS;
foreach my $file (@ARGV) {
	if (-d $file) {
		warn "$Program: '$file' is a directory\n";
		$rc = EX_FAILURE;
		next;
	}
	my $fh;
	unless (open $fh, '<', $file) {
		warn "$Program: cannot open '$file': $!\n";
		$rc = EX_FAILURE;
		next;
	}
	rev($fh);
	if ($!) {
		warn "$Program: '$file': $!\n";
		$rc = EX_FAILURE;
	}
}
rev(*STDIN) unless @ARGV;
exit $rc;

sub rev {
	my $fh = shift;
	while (<$fh>) {
		chomp;
		my $r = reverse;
		print $r, $/;
	}
}

sub usage {
	print <<EOF;
Usage: $Program [OPTION] [FILE]...

Reverse lines of the named file(s) or the text input on STDIN

Options:
	-v    Print version number, then exit.

EOF
	exit EX_FAILURE;
}

__END__

=pod

=head1 NAME

rev - reverse lines of a file

=head1 SYNOPSIS

rev [-v] [file]...

=head1 DESCRIPTION

The rev utility copies the specified files to the standard output,
reversing the order of characters in every line.  If no files are
specified, the standard input is read.

=head2 OPTIONS

I<rev> accepts the following options:

=over 4

=item  -v

Print version number then exit

=back

=head1 BUGS

I<rev> has no known bugs.

=head1 AUTHOR

This Perl implementation of I<rev> was written by Andy Murren,
I<andy@murren.org>.

=head1 COPYRIGHT and LICENSE

This program is covered by the GNU Public License (GPL).
See I<http://www.gnu.org/copyleft/gpl.html> for complete detail of the license.

=cut
