首页 > 解决方案 > Perl从数组中输出连续的字符串

问题描述

我有一个可以打印为“abcd”的数组,但是我试图将其打印为“a>ab>abc>abcd”。我无法在我拥有的 foreach 循环中找出我需要的嵌套循环。我需要什么循环才能以这种方式打印它?

my $str = "a>b>c>d";
my @words = split />/, $str;

foreach my $i (0 .. $#words) {
print $words[$i], "\n";
}

谢谢你。

标签: arraysperlforeach

解决方案


您的想法是正确的,但不是在位置 i 打印单词,而是要打印位置 0 和 i(包括)之间的所有单词。此外,您的输入可以包含多个字符串,因此请遍历它们。

use warnings;

while (my $str = <>) {              # read lines from stdin or named files
  chomp($str);                      # remove any trailing line separator

  my @words = split />/, $str;      # break string into array of words
  foreach my $i (0 .. $#words) {
    print join '', @words[0 .. $i]; # build the term from the first n words
    print '>' if $i < $#words;      # print separator between terms (but not at end)
  }

  print "\n";
}

还有许多其他的编写方式,但希望这种方式可以帮助您了解正在发生的事情以及原因。祝你好运!


推荐阅读