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

Something like this is a bit more generic
my @list_in_html = map_by_index [ sub { "<li>$_</li>" }, last => sub { qq!<li class="last">$_</li>! }, ], @list; my @list_in_html = map_by_index [ sub { "<li>$_</li>" }, $#list => sub { qq!<li class="last">$_</li>! }, ], @list;
where the first sub is the default, and last (or $#list) is applied only for the last element.

Or using List::MapList (which could be optimized)

my @list_in_html = maplist( [ ( sub { "<li>$_</li>" } ) x ( @list - 1 ), sub { qq!<li class="last">$_</li>! }, ], @list );

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

    The maplist solution looks really sweet. And it's obviously far more generic than mine. But I have a little problem with the fact that it makes an array (of subrefs) equal in size to the input list. This could be quite expensive. Maybe it should be able to take a "sparse array" (i.e. hash) as an alternative...

    Where does that map_by_index come from?

    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?
      It doesn't actually exist :) but hopefully you see how/what it would do :)