用perl循环连接数组项

用户名

我有一个带有x个项目的数组:

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

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

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

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

Ngoan Tran

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章