user5861285
user5861285

Reputation:

Join array items in loop with perl

I have an array with x items:

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

Now i want to ietrate this array. Every Loop should append an entry:

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

How i can realize this with perl?

Upvotes: 1

Views: 1346

Answers (3)

Ngoan Tran
Ngoan Tran

Reputation: 1527

You can try with this solution:

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

The result as you expect.

output

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



Update

That should have been

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;
}

output

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

Upvotes: 0

Borodin
Borodin

Reputation: 126722

Do you need the individual paths, or do you just want to join all the segments?

To do the latter you can just write

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

(By the way, that's an awful identifier. The @ tells us that it's an array so the arr adds nothing. I don't know what your data represents, but perhaps @segments would be better.)

But if you need the loop, you can do this

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;
}

output

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

Note that this is essentially the same algorithm as Dave Cross shows but I have used a standard block for loop as I imagine that you will want to do something with the paths other than printing them, and I have removed the numbering as I think that was just an illustrative part of your question.

Upvotes: 2

Dave Cross
Dave Cross

Reputation: 69224

Here's a slightly more idiomatic solution.

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

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

Upvotes: 2

Related Questions