2

I want to filter own output without writing separate program for that. There is perl5 solution that may be adapted. Is there something better that can be done like that new language supports?

head(100);
while (<>) {
  print;
} 

sub head {
 my $lines = shift || 20;
 return if $pid = open(STDOUT, "|-");
 die "cannot fork: $!" unless defined $pid;
 while (<STDIN>) {
    print;
    last unless --$lines ;
 } 
 exit;
}
Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
teodozjan
  • 913
  • 10
  • 35

1 Answers1

2

@raiph comment helped me a lot

It is possible to substitute OUT class with anything needed. This preserves laziness that IO::Capture::Simple seem not to have yet.

This example does very simple duplicated lines cut out

my $undecorated_out = $*OUT;
my $decorated_out = class {
    my @previous="nothing";
    method print(*@args) {
        my @toprint;
        if @args[0] eq @previous[0] {
            @toprint = ("...\n")
        }else{
            @toprint = @args;
        }
        $undecorated_out.print(@toprint) ;
        @previous = @args unless @args[0] eq "\n";
    }
    method flush {}
}
$*OUT = $decorated_out;
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
teodozjan
  • 913
  • 10
  • 35