Perl从数组输出连续字符串

时间:2019-04-17 16:08:47

标签: arrays perl foreach

我有一个数组,可以打印为“ 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";
}

谢谢。

4 个答案:

答案 0 :(得分:4)

您的想法是正确的,但您不想打印位置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";
}

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

答案 1 :(得分:3)

一个班轮:

form.valueChanges.forEach((v)=>console.log(v))

答案 2 :(得分:1)

这就是我最终得到的结果,这是我能够理解并获得所需输出的唯一方法。

use strict;
use warnings;

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

my $j = $#words;
my $i = 0;
my @newtax; 
while($i <= $#words){
        foreach my $i (0 .. $#words - $j){
            push (@new, $words[$i]);
    }

    if($i < $#words){
        push(@new, ">");
    }
    $j--;
    $i++;
}

print @new;

此输出“ a> ab> abc> abcd> abcde> abcdef> abcdefg”

答案 3 :(得分:1)

我会这样:

#!/usr/bin/perl

use strict;
use warnings;

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

$" = '';
my @new_words;

push @new_words, "@words[0 .. $_]" for 0 .. $#words;

print join '>', @new_words;

几件事要解释。

Perl将在双引号字符串中扩展数组变量。像这样:

@array = ('x', 'y', 'z');
print "@array";

将打印x y z。注意元素之间有空格。元素之间插入的字符串由$"变量控制。因此,通过将该变量设置为空字符串,我们可以删除空格,因此:

$" = '';
@array = ('x', 'y', 'z');
print "@array";

将打印xyz

最复杂的行是:

push @new_words, "@words[0 .. $_]" for 0 .. $#words;

那只是一种紧凑的书写方式:

for (0 .. $#words) {
  my $new_word = "@words[0 .. $_]";
  push @new_words, $new_word;
}

我们迭代从0到@words中最后一个索引的整数。每次循环时,我们使用数组切片从数组中获取元素列表,将其转换为字符串(通过将其放在双引号中),然后将该字符串压入@new_words