views:

170

answers:

4

When executing a perl script from the command line how can I ensure that my output doesn't scroll off the screen?

In others words, how do I mimic the functionality of the unix "more" or "less" commands?

+3  A: 

Can't the user just pipe the output to less? That gives them the option of using their favourite pager, or even not using any pager at all, if they prefer that.

Matti Virkkunen
Perhaps the script is interactive at certain points, but the author wants to display a block of text (an EULA or long warning message for example) - piping would not work as expected in this case.
Gavin Brock
First check $PAGER environment variable. /bin/more and /usr/bin/less are two safe fallback options.
Tadeusz A. Kadłubowski
@Gavin Brock: In that case, I'd definitely like to be able to pipe the output, so that I can pipe the EULA to `/dev/null`.
Matti Virkkunen
+6  A: 

The Term::Pager module would seem to be what you're looking for.

gorilla
+1  A: 

As Matti Virkkunen says, it's better that the user pipes your script to less.

A *nix user would expect output in plain text, so (s)he can pipe it to other commands if they need to. Making your script not displaying output as plain text, you user may find your script less usable.

klez
+1  A: 

For quick and dirty can pipe the text to less or more:

my $text = <<'EOD';
Lots
   and
      lots
         of
           text
EOD

my $pager = $ENV{PAGER} || 'less';
open(my $less, '|-', $pager, '-e') || die "Cannot pipe to $pager: $!";
print $less $text;
close($less);

There are various less/more flags to allow the script to continue when it reaches the bottom of the text.

Gavin Brock
It would be much better to use lexical filehandles, and check the user's PAGER environment variable to see if they have a preference over `less`.
Ether
Updated the code. I guess the use of $ENV{PAGER} adds risk that the user can break the script with a messed up environment.
Gavin Brock