word_columner.pl 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 29 August 2012
  4. # Edit: 18 January 2015
  5. # Website: https://github.com/trizen
  6. # Put two or more lines together as columns. (with unicode char width support)
  7. use strict;
  8. use warnings;
  9. use open IO => ':encoding(UTF-8)', ':std';
  10. use Getopt::Std qw(getopts);
  11. my %opt = (
  12. c => 2,
  13. s => 25,
  14. l => 0,
  15. r => 0,
  16. u => 0,
  17. );
  18. getopts('c:s:l:ruh', \%opt);
  19. sub usage {
  20. die <<"USAGE";
  21. usage: $0 [options] [files]
  22. options:
  23. -c <i> : number of columns (default: $opt{c})
  24. -s <i> : number of spaces between words (default: $opt{s})
  25. -l <i> : number of leading spaces (default: $opt{l})
  26. -u : use the unicode char width feature
  27. -r : reverse columns
  28. Example: perl $0 -l 3 -s 40 file.txt > output.txt
  29. USAGE
  30. }
  31. usage() if $opt{h} or not @ARGV;
  32. foreach my $file (@ARGV) {
  33. open my $fh, '<', $file
  34. or do { warn "$0: Can't open file '$file' for read: $!\n"; next };
  35. my @lines;
  36. while (<$fh>) {
  37. chomp;
  38. push @lines, $_;
  39. if ($. % $opt{c} == 0 || eof $fh and @lines) {
  40. my @cols = $opt{r} ? reverse splice @lines : splice @lines;
  41. my $format = ' ' x $opt{l};
  42. if ($opt{u}) {
  43. require Text::CharWidth;
  44. foreach my $i (0 .. $#cols - 1) {
  45. my $diff = abs(Text::CharWidth::mbswidth($cols[$i]) - length($cols[$i]));
  46. $format .= "%-" . ($opt{s} - $diff) . 's';
  47. }
  48. }
  49. else {
  50. $format = "%-$opt{s}s " x $#cols;
  51. }
  52. $format .= "%s\n";
  53. printf $format, @cols;
  54. }
  55. }
  56. }