Reputation:
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:
How i can realize this with perl?
Upvotes: 1
Views: 1346
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.
.mother
1.mother/child1
2.mother/child1/child2
3.mother/child1/child2/child3
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;
}
1.mother
2.mother/child1
3.mother/child1/child2
4.mother/child1/child2/child3
Upvotes: 0
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;
}
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
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