EdwardG has asked for the wisdom of the Perl Monks concerning the following question:
What I want to do is create a string from an array, joining each element with a different string depending on the values of the elements being joined.
For example, I want to join this list
0,1,0,1to get this result:
__RESULT__ 0:10:1
My first thought was to assume that join worked iteratively on the elements of the array, and so if I had a matching array I could do this
my @a = (':','',':',''); my $i=0; print join $a[$i++], 0,1,0,1; # Wrong, $i isn't incremented
But $i is not incremented during the execution of join, and so the first element of @a is used to concatenate all my list items:
__RESULT__ 0:1:0:1
If join did work iteratively, I would expect it to set $_ for each iteration, and if this was true I could do this
print join $_ ? '' : ':', 0,1,0,1; # Wrong, $_ isn't set __RESULT__ 0:1:0:1
I also realised that I might be thinking naively about the iteration - that each element is not handled in isolation, but in pairs like this
(start) 1. join $a[0] and $a[1] 2. join $a[1] and $a[2] 3. join $a[2] and $a[3] (finished)
And that if indeed join works on pairs of elements, setting $_ doesn't make sense - which element would be used for each iteration? (As a side thought I wonder if it would make sense to set $a and $b, like in a sort.)
But that doesn't seem to be how join works. I suppose it could also be that join does work iteratively, and on pairs, but that it only evaluates the EXPR part of join just once.
I can just forget about join and rewrite like this
my $j = ''; $j .= $_ ? length $j ? ":$_" : $_ : $_ for (0,1,0,1); print $j; __RESULT__ 0:10:1
But I'm surprised that there isn't some join trick that would do the job more succinctly.
Am I thinking straight? Please tell me what I'm overlooking!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Surprised by join
by halley (Prior) on Jun 08, 2004 at 13:19 UTC | |
by EdwardG (Vicar) on Jun 08, 2004 at 13:27 UTC | |
|
Re: Surprised by join
by eserte (Deacon) on Jun 08, 2004 at 13:44 UTC | |
by EdwardG (Vicar) on Jun 08, 2004 at 13:47 UTC | |
by eserte (Deacon) on Jun 08, 2004 at 14:11 UTC | |
by Roy Johnson (Monsignor) on Jun 08, 2004 at 16:53 UTC | |
by EdwardG (Vicar) on Jun 08, 2004 at 19:10 UTC | |
|
Re: Surprised by join
by itub (Priest) on Jun 08, 2004 at 15:01 UTC | |
|
Re: Surprised by join
by Abigail-II (Bishop) on Jun 08, 2004 at 15:20 UTC | |
|
Re: Surprised by join
by pelagic (Priest) on Jun 08, 2004 at 13:40 UTC | |
by EdwardG (Vicar) on Jun 08, 2004 at 13:43 UTC | |
by pelagic (Priest) on Jun 08, 2004 at 13:54 UTC | |
by EdwardG (Vicar) on Jun 08, 2004 at 13:58 UTC | |
by pelagic (Priest) on Jun 08, 2004 at 14:01 UTC | |
by dragonchild (Archbishop) on Jun 08, 2004 at 15:16 UTC |