in reply to Variant of map for special-casing the last item

I probably would have this in 5.8:

$ cat sentinel_58.pl #!perl use strict; use warnings; my @in = qw{start middle end}; my $i = 0; print map { join($_, ($i++ == $#in ? q{<li class="last">} : q{<li>}), q{</li>} +); } @in; $ sentinel_58.pl <li>start</li><li>middle</li><li class="last">end</li>

And here's much the same offering for newer Perl versions:

$ cat sentinel_512.pl #!perl use 5.12.0; use warnings; my @in = qw{start middle end}; say map { state $i = 0; join($_, ($i++ == $#in ? q{<li class="last">} : q{<li>}), q{</li>} +); } @in; $ sentinel_512.pl <li>start</li><li>middle</li><li class="last">end</li>

-- Ken

Replies are listed 'Best First'.
Re^2: Variant of map for special-casing the last item
by jdporter (Paladin) on Oct 26, 2010 at 13:44 UTC

    I definitely like the use of a state variable way more than the 5.8 approach. But what I still don't like about this and similar solutions is that they introduce a dependency inside the code block on the value of $#in. What if the input list isn't in an array variable? That's right — you can store it in a temporary. Well, that's what my solution does for you, keeping that mess out of your code.

    What is the sound of Windows? Is it not the sound of a wall upon which people have smashed their heads... all the way through?

      I wrote the 5.12 code first then, realising many people haven't moved past 5.8 yet, wrote the second version - I probably should have posted them in that order. Being able to confine the scope of a variable to a map (or similar) block via state in this way is a nice feature.

      I agree, this solution is not directly applicable to situations like map {...} qw{...}.

      -- Ken