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!
In reply to Surprised by join by EdwardG
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |