Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Paging on input/file

by hotshot (Prior)
on Aug 04, 2004 at 07:57 UTC ( [id://379925] : perlquestion . print w/replies, xml ) Need Help??

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

Hi all!

I have LONG input I wish to display to the console (from my perl script), sometimes it's a content of a file and sometime it can be a very big hash/list.
How can I implement a pager (like less or more), or is there a ready module that can help me here?
Is using Linux less as follows is a good solution?
system("less $file");

Replies are listed 'Best First'.
Re: Paging on input/file
by rhythmicus (Sexton) on Aug 04, 2004 at 08:17 UTC
Re: Paging on input/file
by broquaint (Abbot) on Aug 04, 2004 at 08:20 UTC
    You could try IO::Pager for your text paging needs.


Re: Paging on input/file
by trantor (Chaplain) on Aug 04, 2004 at 08:20 UTC

    If your program is not interactive, just follow the *NIX tradition, i.e. just print your output and let the user decide to page it if necessary, like: | less

    If your program is interactive (i.e. it waits for input from the user) then this is not feasible. You can either write your own little pager using for example Curses, or you can yet again follow a well established *NIX convention and run the user's favourite pager, which is usually stored in $ENV{PAGER}.

    Using the user's pager has the definite advantages of not having to reinvent the wheel (think lazy (-;) and presenting the user with a well-known interface for viewing long files.

    If you use system, it is a good idea to pass a list and not a single scalar as an argument: the single scalar could be interpreted by the shell (for example if it has wildcards) with possibly nasty or anyway unwanted side effects.

Re: Paging on input/file
by tachyon (Chancellor) on Aug 04, 2004 at 13:14 UTC

    If you want to roll your own it is easily achieved using % and <>. Piping to more/less is more or less traditional ;-) I recommend you use one of the modules if you want robust and portable, although a straight pipe to more will work on *nix and Win32.

    my $lines = 2; while(<DATA>) { chomp; print; $. % $lines == 0 ? <> : print "\n"; } __DATA__ foo bar baz boo