繁体   English   中英

用perl循环加入数组项

[英]Join array items in loop with perl

我有一个包含x个项目的数组:

my @arr= qw( mother child1 child2 child3);

现在我想模仿这个数组。 每个循环都应附加一个条目:

  1. 母亲
  2. 母亲/孩子1
  3. 母亲/孩子1 /孩子2
  4. 母亲/儿童1 /儿童2 /儿童3

我如何用Perl来实现这一点?

这是一个比较惯用的解决方案。

my @arr = qw[mother child1 child2 child3];

say $_ + 1, '. ', join ('/', @arr[0 .. $_]) for 0 .. $#arr;

您需要单独的路径,还是只想加入所有细分市场?

要做到后者,你可以写

my $path = join '/', @arr;

(顺便说一句,这是一个糟糕的标识符。 @告诉我们这是一个数组,因此arr添加任何内容。我不知道您的数据代表什么,但@segments可能会更好。)

但是,如果您需要循环,则可以执行此操作

use strict;
use warnings 'all';
use feature 'say';

my @arr= qw( mother child1 child2 child3 );

for my $i ( 0 .. $#arr ) {

    my $path = join '/', @arr[0 .. $i];

    say $path;
}

输出

mother
mother/child1
mother/child1/child2
mother/child1/child2/child3

请注意,这基本上与Dave Cross展示的算法相同,但是我使用了一个标准for循环块for因为我想您会希望对路径进行除打印之外的其他操作,并且我删除了编号,因为我认为那是只是您问题的一个说明性部分。

您可以尝试使用以下解决方案:

my @arr= qw( mother child1 child2 child );
my $content;
my $i;
foreach (@arr){
  $content .= '/' if ($content);
  $content .= $_;
  print "$i.$content\n";
  $i++;
}

预期的结果。

输出

.mother
1.mother/child1
2.mother/child1/child2
3.mother/child1/child2/child3



更新资料

那应该是

use strict;
use warnings 'all';

my @arr= qw( mother child1 child2 child3 );

my $content;
my $i = 1;

foreach ( @arr ) {

  $content .= '/' if $content;
  $content .= $_;

  print "$i.$content\n";

  ++$i;
}

输出

1.mother
2.mother/child1
3.mother/child1/child2
4.mother/child1/child2/child3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM