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:
- mother
- mother/child1
- mother/child1/child2
- mother/child1/child2/child3
How i can realize this 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:
How i can realize this with perl?
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.
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
$content .= '/' if ($i>1) is better written as $content .= '/' if $content, so the $i variable is unnecessary.use strict and use warnings 'all' in place as you should have then you would have seen the warning message Use of uninitialized value $i in concatenation (.) or string