On Jun 6, Alan F. Larimer, Jr. said:

>>   #!/usr/bin/perl -w
>> 
>>   use strict;
>> 
>>   sub pager {
>>     my ($fh, $func, $pause, $lines) = @_;  # grab the args
>>     local (*READ, *WRITE, *FH, *SAVE);  # create local to use here

These filehandles are only needed locally.

>>     pipe READ, WRITE;  # open the pipes for in and out

Create an output filehandle, *WRITE, and the input filehandle *READ that
reads from it.

>>     *FH = $fh;         # ??? Help me here, assigns reference
>>                        # of $fh ???

We pass the filehandle to use as a reference to it (\*STDOUT), so here, we
assign it to another filehandle we can use.

>>     open SAVE, ">&FH";  # output SAVE

We're copying the file-descriptor of FH to SAVE, so that SAVE goes where
FH does (and continues to, even after we change FH, below).

>>     open FH, ">&WRITE"; # also output FH
>>                          #why two above?

Now, we're redirecting FH to go to the WRITE filehandle.

We do this so that we can (temporarily) capture output to a
specific filehandle (the one we pass into the function), and then restore
the filehandle once that data has been gotten.

We're basically saying:

  1. save FH
  2. redirect FH to WRITE
  3. do something that writes to FH (and actually goes to WRITE)
  4. restore FH

We print to WRITE so that we can read from... READ.

>>     my $old = select FH; # save FH

Default print() goes to FH, and we remember which filehandle was
select()ed before.

>>     $func->();  # ??? Help here also, does this call passed func?

This calls the function reference (sub { ... } or \&foo) that we
passed.  This is the part that does some writing that we want to capture.

>>     close FH;     # close FH
>>     close WRITE;  # close ouput
>> 
>>     open FH, ">&SAVE";  # reopen FH, as output, why?
>>     close SAVE;  # close SAVE, which did what?

This is explained above -- we needed to temporarily redirect FH, and now
we need to restore it.

>>     while (<READ>) {
>>       print;
>>       $pause->() if $. % $lines == 0; # understand %, but
>>     }                                 # confused by $pause->()

The code reference in $pause is the thing that we use to pause the
scrolling, to act as the pager.  Here, I passed sub { <STDIN> }, which
means "wait for input from STDIN".  You might use sub { sleep 1 }, or
something like that.

>>      
>>     close READ;
>> 
>>     select $old;  # seld old FH
>>   }
>> 
>>   pager(\*STDOUT, sub { print `ls -lag` }, sub { <STDIN> }, 20);

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
I am Marillion, the wielder of Ringril, known as Hesinaur, the Winter-Sun.
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734
**      Manning Publications, Co, is publishing my Perl Regex book      **

Reply via email to