summaryrefslogtreecommitdiff
path: root/019
diff options
context:
space:
mode:
authorGuillermo Ramos2019-08-01 08:07:57 +0200
committerGuillermo Ramos2019-08-01 08:07:57 +0200
commitd1ca59ce3b49a3f12ae7aadff5217e74350816cb (patch)
tree97774bd0c56fb9221e8746a07f3ad03d6cfe064b /019
parente91dfe6e10f8192197ac5c81c8c82fafd1b377f6 (diff)
downloadperlweekly-d1ca59ce3b49a3f12ae7aadff5217e74350816cb.tar.gz
[019#2]
Diffstat (limited to '019')
-rwxr-xr-x019/ch2.pl31
1 files changed, 31 insertions, 0 deletions
diff --git a/019/ch2.pl b/019/ch2.pl
new file mode 100755
index 0000000..4f110cf
--- /dev/null
+++ b/019/ch2.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/env perl
+#
+# Write a script that can wrap the given paragraph at a specified column using
+# the greedy algorithm.
+#
+# (https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_number_of_lines).
+################################################################################
+
+use strict;
+use warnings;
+
+my $COLUMN = shift or die "Usage: $0 <column> [file]\n";
+
+my @words;
+while (<>) {
+ push @words, split " ", $_;
+}
+
+my $col = 0;
+my @out_line;
+for my $word (@words) {
+ my $word_len = length $word;
+ if ($col + $word_len + 1> $COLUMN && @out_line) {
+ print "@out_line\n";
+ @out_line = ();
+ $col = 0;
+ }
+ push @out_line, $word;
+ $col += $word_len + 1;
+}
+print "@out_line\n";