my $line2 = ("My cat Garfield");
my $leng2 = length $line2;
my $longmatch;
my $post = 0;
my $letter = 1;
for(my $post = 0; $post < $leng2; $post++) {
for($letter = 1; $letter <= $leng2; $letter++) {
$longmatch = (substr($line2,$post,$letter));
print $longmatch, "\n";
}
}
如何消除重复的行?
答案 0 :(得分:6)
使用C风格的循环 - for (my $i = 0; $i < 10; $i++)
- 不是perl方式。只需使用for my $i (0 .. 10)
代替。
在此示例中,我在后脚本循环中使用隐式变量$_
,并使用say
而不是print来获取自动换行结束:
use v5.10; # used to enable feature say
my $cat = 'my cat is Garfield';
say substr($cat, 0, $_) for 1 .. length($cat);
答案 1 :(得分:3)
您的substr()参数可能不对。
my $x = "my cat is Garfield";
for (my $i = 1; $i <= length($x); $i++) {
print substr($x, 0, $i) . "\n";
}
答案 2 :(得分:1)
my $a= 'my cat is Garfield';
for(my$i = 0; $i <= length($a); ++$i)
{
printf("%.*s\n", $i, $a);
}
答案 3 :(得分:1)
print substr( $str, 0, $_ ), "\n" foreach 1..( length $str );
答案 4 :(得分:1)
假设当你说“我怎么能消除重复的线?”时,你的意思是“消除看起来与前一行相同的线,因为它们有一个尾随空格”,以下可能会做你想要的。请注意我已经无耻地复制了以前的贡献,以致获得了答案:)
use v5.10; # used to enable feature say
my $cat = 'my cat is Garfield';
my $last = "";
for (1 .. length($cat) ){
my $text = substr($cat, 0, $_);
my $trim = $text;
$trim =~ s/\s+$//;
say $trim unless ($trim eq $last);
$last = $trim;
}
答案 5 :(得分:-3)
my $a = "your string";
map { print substr($a, 0, $_) . "\n" } (1..length($a));