Perl Programming more or less

brian_d_foy on 2002-11-16T08:14:49

I realized that I almost always use a pipe to `more` (or `less`) with some of my scripts. That is fairly dumb of me---I should make the computer do the work. My first thought was to create a shell alias. That might be a good way to do it, but I have also been meaning to figure out how to make a program use `more` directly.

I do not know why I have not done this before. Although I think everyone but me must have already known this, it turns out to be pretty simple.

#!/usr/bin/perl

my $Pager = $ENV{PAGER} || do { chomp( my $m = `which more` ); $m };

die "Can't execute pager [$Pager]\n" unless -x $Pager;

$| = $\ = "\n";

open OUT, "| $Pager";

my $count = 0;

while( $count < 100 ) { print OUT $count++; }

close OUT;



The only thing that confused me initially was the close(). Without it, the terminal gets confused (at least with bash under either Mac OS X and FreeBSD). I am not a unix systems sort, so I cannot tell you why that is, and as long as it works I am on to the next thing.

With a little more magic, which I do not show, I can turn this into something that defaults to STDOUT, which means I have to get rid of the |. After that, I might throw in something with one of my favorite tricks---testing for an interactive session.

Interactive sessions typically have a STDIN hooked up to a terminal. I do not think this is a sufficient way to determine if the session is interactive---there must be some exception---but it works most of the time. The -t file test operator returns true if the filehandle is hooked up to a terminal.

my $interactive = -t STDIN;


If things are not interactive, I do not want to us e a pager. I might want to use STDOUT (cron will mail it to me), or mail, or /dev/null.

But, in the end, I just want my journal reader to page the output.