package IO::Handle;

sub is_chomped { tie *{ $_[0] }, 'Perl6::FileHandle', @_ }
sub is_not_chomped { untie *{ $_[0] } }


package Perl6::FileHandle;

$VERSION = '0.0.1';

use Tie::Handle;
@ISA = 'Tie::StdHandle';


sub TIEHANDLE {
  my ($class, $real, $sep) = @_;

  return bless [ undef, 1, @_ > 2 ? $sep : () ], "${class}::ARGV"
    if $real == \*ARGV;

  defined fileno($real) or die "$real has no file descriptor!";
  open my($fh), "<&" . fileno($real) or die "can't dup to $real: $!";

  bless [ $fh, @_ > 2 ? $sep : () ], $class;
}


sub READLINE {
  my $self = shift;
  my $fh = $self->[0];
  return if eof $fh;

  local $/ = $self->[1] if @$self == 2;
  my @lines = map { chomp; $_ } wantarray ? <$fh> : scalar <$fh>;
  return wantarray ? @lines : $lines[0];
}


DESTROY { }


# AUTOLOAD {
#   my $self = shift;
#   my $fh = $self->[0];
#   (my $meth = $AUTOLOAD) =~ s/.*::/Tie::StdHandle::/;
#   $fh->$meth(@_);
# }


package Perl6::FileHandle::ARGV;

@ISA = qw( Perl6::FileHandle );


sub READLINE {
  my $self = shift;
  my $fh = $self->[0];

  if (not defined $fh or eof $fh) {
    $self->[1] = 0, push @ARGV, "-" if $self->[1] and not @ARGV;
    $self->[1] = 1, undef($self->[0]), return unless @ARGV;

    my $file = shift @ARGV;
    open $fh, $file or die "Can't open $file: $!";
    $self->[0] = $fh;
  }

  local $/ = $self->[1] if @$self == 3;
  my @lines = map { chomp; $_ } wantarray ? <$fh> : scalar <$fh>;
  return wantarray ? @lines : $lines[0];
}


1;


=head1 NAME

Perl6::FileHandle - auto-chomping

=head1 SYNOPSIS

  use Perl6::FileHandle;
  
  # every read from <STDIN> is auto-chomped
  # using the value of $/ when STDIN is read
  is_chomped STDIN;
  
  # every read from <$fh> is auto-chomped
  # and the record separator is "" (paragraph mode)
  open my($fh), "< .cshrc" or die ".cshrc: $!";
  is_chomped $fh "";
  
  # first "paragraph"
  my $first_block = <$fh>;
  
  # now $fh's record separator is undef
  is_chomped $fh undef;
  
  # even works for magical ARGV
  is_chomped ARGV;

=head1 DESCRIPTION

