This module, Perl6::FH, allows you to write code like:package IO::Handle; sub is_chomped { tie *{ $_[0] }, 'Perl6::FH', @_ } sub is_not_chomped { untie *{ $_[0] } } package Perl6::FH; use Tie::Handle; sub TIEHANDLE { my ($class, $real, $sep) = @_; ### updated (@_ == 3) -> (@_ > 2) 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: $!"; ### updated (@_ == 3) -> (@_ > 2) bless [ $fh, @_ == 3 ? $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::FH::ARGV; @ISA = qw( Perl6::FH ); 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;
You can also specify the separator for THAT specific filehandle:use Perl6::FH; is_chomped STDIN; while (<STDIN>) { # $_ has already been chomp()ed # with whatever $/ is right now }
And you can turn it off, and return the filehandle to its normal status:is_chomped STDIN ""; # paragraph mode is_chomped STDIN "%%\n"; # fortune mode
The module has been updated to work properly for ARGV (which required some munging):is_not_chomped STDIN;
is_chomped ARGV; while (<>) { # $_ is chomped }
In reply to (updated) Perl6::FH by japhy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |