in reply to Surprised by join

How about this myjoin function:
sub myjoin (&@) { my $sub = shift; my $res = $_[0]; for my $i (1 .. $#_) { $res .= $sub->($_[$i-1], $_[$i]) . $_[$i]; } $res; } my @a = (':','',':',''); my $i=0; print myjoin { $a[$i++] } 0,1,0,1; # Right now
You can even change the separator depending of its neighbors, which are supplied as arguments to the code block.

Replies are listed 'Best First'.
Re^2: Surprised by join
by EdwardG (Vicar) on Jun 08, 2004 at 13:47 UTC

    ++ I like this, although I'm starting to think that I had just misunderstood join and should probably go with an alternate solution rather than shoehorn join to my way of thinking.

     

      Somewhere else in this thread $a and $b were mentioned. The snippet above could be changed to use this. Instead of

      $res .= $sub->($_[$i-1], $_[$i]) . $_[$i];

      it would be

      local $a = $_[$i-1]; local $b = $_[$i]; $res .= $sub->() . $_[$i];
      (Untested)
Re^2: Surprised by join
by Roy Johnson (Monsignor) on Jun 08, 2004 at 16:53 UTC
    Your approach was exactly what the OP was looking for (++), but your example has some excess baggage that made it confusing for me. Simplified:
    sub myjoin (&@) { my $sub = shift; my $res = shift; $res .= $sub->() . $_ for (@_); $res; }
    Update: Oh, I see: the arguments to sub were to stand in for $a and $b (a la sort), in case the user wanted to have that kind of flexibility in the sub.

    Is the thread title a C.S. Lewis reference, I wonder?


    The PerlMonk tr/// Advocate
      Is the thread title a C.S. Lewis reference, I wonder?

      It is, well spotted.