我正试图打破300个字符,它确实很好,但我不希望它在一个单词的中间打破。我想找到一个单词的结尾或下一个可用的空格。任何帮助将不胜感激。
foreach (@$comp) {
my $c = $_;
$c->{reviews} = ($c->{reviews} - 1);
my $stars;
if($c->{reviews} == 0) {
$stars = 0;
} else {
$stars = int($c->{reviews_total} / $c->{reviews});
}
$c->{stars} = $stars;
if($c->{title}) {
$c->{name} = $c->{title};
$c->{event} = "FOO";
}
$c->{description} =~ s/BREAK//g;
my (@desc) = split(//, $c->{description});
my $adesc;
my $rowc = 0;
my $count = 0;
while($count < 300 ) {
$adesc .= @desc[$count];
$rowc++;
$count++;
}
$c->{description} = $adesc;= '...';
}
答案 0 :(得分:9)
让我们看看perldoc perlfaq4
要说的内容:
如何重新格式化段落?
使用
Text::Wrap
(标准Perl发行版的一部分):use Text::Wrap; print wrap("\t", ' ', @paragraphs);
您提供给
Text::Wrap
的段落不应包含嵌入式 换行。Text::Wrap
不能证明这些行是正确的(冲洗右)。
但是如果你不喜欢它呢?
访问CPAN
use Text::Wrap::Smart 'wrap_smart';
use feature 'say';
my $text = 'lorem ipsum dolor sit amet' x 500;
my $options = {
no_split => 1, # Activates 'fuzzy matching'
max_msg_size => 300,
};
say for wrap_smart( $text, $options );
答案 1 :(得分:3)
怎么样:
my $str = q!A very long string to be wrapped on whitespace!;
my $len = 15; #for test. In your case, let $len=300
my @l = grep{s/^\s+//;$_ ne ''}split(/(.{1,$len})(?=\s)/, $str);
dump@l;
<强>输出:强>
("A very long", "string to be", "wrapped on", "whitespace")
答案 2 :(得分:0)
您可以使用:
$str = "my big string blah blah...";
for ( $i = 300; substr( $x, $i, 1 ) =~ /\w/; $i++ ) { };
$str = substr( $str, 0, $i );
答案 3 :(得分:0)
perl -nwE 'say for m/(.{0,75} )/g' textsample2.txt
HAMLET: To be, or not to be--that is the question: Whether 'tis nobler in
the mind to suffer The slings and arrows of outrageous fortune Or to take
...
像魅力一样工作。除非你的文字中有非常长的单词,否则只需调整数字即可。
当然,您必须首先删除所有旧的换行符。所以,像:
sub wrap_text {
my ($text, $len) = @_;
$text =~ s/[\r\n]+//g; # yeah, removing \r while at it
return ( $text =~ m/(.{0,$len} )/g );
}
然后:
say for wrap_text($text, 300);