I thought it might be useful to have an equivalent to join that could stitch a LIST together with an EXPR that actually varied. Just for fun, and not expecting it to work, I first tried supplying a tied scalar incrementor as the first argument to join but, to my great surprise, it did produce a string with a varying EXPR joining the LIST elements. This code
use strict; use warnings; use feature qw{ say }; # =========== package Incrementor; # =========== use Tie::Scalar; our @ISA = qw{ Tie::StdScalar }; sub TIESCALAR { my( $pkg, $value ) = @_; $value //= 0; return bless \ $value, $pkg } sub FETCH { my $self = shift; return ${ $self } ++; } package Main; my @arr = qw{ a b c d e }; tie my $inc, q{Incrementor}; say join $inc, @arr; say q{-} x 20; say join $inc, @arr;
produces this output
a1b2c3d4e -------------------- a6b7c8d9e
Note that the invocation of join seems to consume the first iteration before actually constructing the string. The documentation says
Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string.
and the wording looks the be the same for for all versions. My expectation was that the EXPR would be evaluated once and the invariant result used between every element of the LIST. This doesn't appear to be the case for the following perl versions - 5.8.8, 5.10.1 and 5.14.2 on various Linuxen or Cygwin and 5.16.1 on Windows 7. However, under 5.18.2 on Mint 17 I do get what I was expecting
a0b0c0d0e -------------------- a1b1c1d1e
I don't have 5.20 installed anywhere so can't test on that. Is the behaviour of join with a tied scalar prior to 5.18.2 correct but not clearly explained in the documentation or is it a bug that has now been fixed?
Cheers,
JohnGG
In reply to Undocumented join() feature, now defunct? by johngg
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |