$comment = 'This is a test. This is only a test. If this were a real emergency, you would have been informed. Just kidding. It was a real emergency after all.';
print wordwrap($comment, 50);
sub wordwrap {
my ($string, $max, $breaker) = @_;
# set defaults
$max = quotemeta($max) || 70;
$breaker //= "\n";
$string =~ s/(.{$max}[^\s]*)\s+/$1$breaker/;
return $string;
}
$comment = 'This is a test. This is only a test. If this were a real emergency, you would have been informed. Just kidding. It was a real emergency after all.';
print &wordwrap($comment, 50);
sub wordwrap {
my ($string, $max) = @_;
my $out="";
my $cheese=0;
@snack = split(/ /, $comment);
foreach $s (@snack) {
$out.=$s . " ";
$cheese+=length($s);
$out.="\n" if $cheese > $max; #or whatever the wrap is...
$cheese=0 if $cheese > $max;
# print "$cheese, $max $out\n";
}
return($out);
}
sub wordwrap {
my ($string, $max, $breaker) = @_;
my @arr;
$max //= 70;
$breaker //= "\n";
$len = length($string) / $max;
for ($x = 0; $x < $len; $x++) {
$arr[$x] = $string =~ s/^(.{$max}[^\s]*)\s+.*/$1/r;
$string =~ s/^\Q$arr[$x]\E\s+//;
}
return join($breaker, @arr);
} sub wordwrap {
my ($string, $max, $breaker) = @_;
my @arr;
$max //= 70;
$breaker //= "\n";
$len = length($string) / $max;
for ($x = 0; $x < $len; $x++) {
$arr[$x] = $string =~ s/^(.{$max}[^\s]*)\s+.*/$1/r;
$string = substr($string, length($arr[$x]));
}
return join($breaker, @arr);
}
sub wordwrap {
my ($string, $max, $breaker, $start, @arr) = @_;
$max //= 70;
$breaker //= "\n";
$start = 0;
$len = int(length($string) / $max);
for (0..$len) {
my $finder = index($string, ' ', $max);
push (@arr, substr($string, $start, $finder));
$start += $finder;
}
return join($breaker, @arr);
}
But I don't really want to import a module with each load of the script for something that might be used 1 in 50 times
Does Perl not support loading modules dynamically and conditionally?
Because use takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a use inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the if [perldoc.perl.org] pragma:
use if $] < 5.008, "utf8";
use if WANT_WARNINGS, warnings => qw(all);
In particular, putting a use inside the false branch of a conditional doesn't prevent it from being processed.
if ($foo eq 'bar') {
use Foo::Bar;
} if ($foo ne 'bar') {
use Foo::Bar;
}