Closure to change output


/ Published in: Perl
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ## Define three types printers: 1.Pipe to less, 2.Output to a file 3.Just print
  2. ##
  3. ##
  4.  
  5. sub getLessPrinter {
  6. my $pout= IO::File->new( "| less" ) or croak "Failed to create less pipe\n";
  7.  
  8. return sub { my $line= shift;
  9. return $pout->print( $line ) if defined $line;
  10. $pout->close(); # undef to close
  11. } # closure
  12. } # getLessPrinter
  13.  
  14. sub getFilePrinter {
  15. my $file= shift;
  16. my $fout= IO::File->new( "> $file" ) or croak "Failed to create file: $file: $!\n";
  17.  
  18. return sub { my $line= shift;
  19. return $fout->print( $line ) if defined $line;
  20. $fout->close(); # undef to close
  21. } # closure
  22. } # getFilePrinter
  23.  
  24. sub getNoLessPrinter {
  25.  
  26. return sub { my $line= shift;
  27. print $line if defined $line;
  28. } # closure
  29. } # getNoLessPrinter
  30.  
  31.  
  32. ## Then select one of the printer
  33. ##
  34. ## my $printer= getFilePrinter( "output.txt");
  35. ## or
  36. ## my $printer= getNoLessPrinter();
  37. ## or
  38. my $printer= getLessPrinter();
  39.  
  40. $printer->( "Something to print.\n");
  41. $printer->( undef ); # to close the stream if needed.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.