home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl502b.zip / lib / Text / Tabs.pm < prev    next >
Text File  |  1995-12-28  |  1KB  |  81 lines

  1. #
  2. # expand and unexpand tabs as per the unix expand and 
  3. # unexpand programs.
  4. #
  5. # expand and unexpand operate on arrays of lines.  Do not
  6. # feed strings that contain newlines to them.
  7. #
  8. # David Muir Sharnoff <muir@idiom.com>
  9. # Version: 9/21/95
  10. #
  11.  
  12. =head1 NAME
  13.  
  14. Text::Tabs -- expand and unexpand tabs
  15.  
  16. =head1 SYNOPSIS
  17.  
  18.     use Text::Tabs;
  19.     
  20.     #$tabstop = 8; # Defaults
  21.     print expand("Hello\tworld");
  22.     print unexpand("Hello,        world");
  23.     $tabstop = 4;
  24.     print join("\n",expand(split(/\n/,
  25.         "Hello\tworld,\nit's a nice day.\n"
  26.         )));
  27.  
  28. =head1 DESCRIPTION
  29.  
  30. This module expands and unexpands tabs into spaces, as per the unix expand
  31. and unexpand programs. Either function should be passed an array of strings
  32. (newlines may I<not> be included, and should be used to split an incoming
  33. string into separate elements.) which will be processed and returned.
  34.  
  35. =head1 AUTHOR
  36.  
  37. David Muir Sharnoff <muir@idiom.com>
  38.  
  39. =cut
  40.  
  41. package Text::Tabs;
  42.  
  43. require Exporter;
  44.  
  45. @ISA = (Exporter);
  46. @EXPORT = qw(expand unexpand $tabstop);
  47.  
  48. $tabstop = 8;
  49.  
  50. sub expand
  51. {
  52.     my @l = @_;
  53.     for $_ (@l) {
  54.         1 while s/^([^\t]*)(\t+)/
  55.             $1 . (" " x 
  56.                 ($tabstop * length($2)
  57.                 - (length($1) % $tabstop)))
  58.             /e;
  59.     }
  60.     return @l if wantarray;
  61.     return @l[0];
  62. }
  63.  
  64. sub unexpand
  65. {
  66.     my @l = &expand(@_);
  67.     my @e;
  68.     for $x (@l) {
  69.         @e = split(/(.{$tabstop})/,$x);
  70.         for $_ (@e) {
  71.             s/  +$/\t/;
  72.         }
  73.         $x = join('',@e);
  74.     }
  75.     return @l if wantarray;
  76.     return @l[0];
  77. }
  78.  
  79. 1;
  80.