Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help with sub (words)

Status
Not open for further replies.

calabama

Programmer
Feb 19, 2001
180
0
0
US
Hello All ,
I found this code in the perl cookbook. So I was tyring to understand how to call it as a sub from a main script.


Thanks

cal


Code:
sub words{
 my ($item, $cols, $rows, $maxlen);
 my ($xpixel, $ypixel, $mask, @data);

 getwinsize();

 # first gather up every line of input,
 # remembering the longest line length seen
 $maxlen = 1;
 while (<>) {
     my $mylen;
     s/\s+$//;
     $maxlen = $mylen if (($mylen = length) > $maxlen);
     push(@data, $_);
 }

 $maxlen += 1;               # to make extra space

 # determine boundaries of screen
 $cols = int($cols / $maxlen) || 1;
 $rows = int(($#data+$cols) / $cols);

 # pre-create mask for faster computation
 $mask = sprintf(&quot;%%-%ds &quot;, $maxlen-1);

 # subroutine to check whether at last item on line
 sub EOL { ($item+1) % $cols == 0 }

 # now process each item, picking out proper piece for this position
 for ($item = 0; $item < $rows * $cols; $item++) {
     my $target =  ($item % $cols) * $rows + int($item/$cols);
     my $piece = sprintf($mask, $target < @data ? $data[$target] : &quot;&quot;);
     $piece =~ s/\s+$// if EOL();  # don't blank-pad to EOL
     print $piece;
     print &quot;\n&quot; if EOL();
 }

 # finish up if needed
 print &quot;\n&quot; if EOL();

 # not portable -- linux only
 sub getwinsize {
     my $winsize = &quot;\0&quot; x 8;
     my $TIOCGWINSZ = 0x40087468;
     if (ioctl(STDOUT, $TIOCGWINSZ, $winsize)) {
         ($rows, $cols, $xpixel, $ypixel) = unpack('S4', $winsize);
     } else {
         $cols = 80;
     }
 }

}

In the begining
Let us first assume that there was nothing to begin with.
 
The following line:

while (<>) {

indicates the input stream is via STDIN. Thus is likely to be run as a command line script. The sub can be called as:

words();

and then when you run your script, just type words then hit control-D to stop.

The output is via a set of Linux specific screen control characters.

Barbie
Leader of Birmingham Perl Mongers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top