in reply to Use of wantarray Considered Harmful

I recently thought wantarray would allow me to create a useful Mason component that would either return data in an array so I could format it element by element -- or return a string of that data pre-formatted. Not a good idea. In fact, Mason components already have a dual nature about their return values -- so I think that adding a decision split in the return value just compounds the problem even more. Here is the Mason code:
<%init> my @foo = $m->comp( '.foo' ); my $foo = $m->comp( '.foo' ); </%init> <%def .foo> <%init> my @array = qw(foo bar baz); return wantarray ? @array : join( '', map "$_<br/>", @array ); </%init> </%def>

Now, so far there are no problems. @foo does contain the unformatted elements and $foo contains a string of the elements pre-formatted. As long as I only use those variable in my "template" then i will have no issue:

<!-- correct --> <ol> %for (@foo) { <li><% $_ %></li> %} </ol> <!-- correct --> <p>foo = <% $foo %></p>

The problem comes when you try to take short cuts and call the component directly from your template. None of these do what you want:

<!-- incorrect --> <p>foo = <& .foo &></p> <!-- incorrect --> <p>foo = <% $m->comp( '.foo' ) %></p> <!-- incorrect --> <p>foo = <% $m->comp( '.foo' ) %></p>

The first is simply a wrong use of Mason* and the 2nd and 3rd return lists. This really is not a problem with wantarray so much as it is a trap that one thinks they can call Mason components in this manner -- and boy wouldn't it sure be great to utilize wantarray to make my call simple? Bzzzzzt. Here's the correct call:

<!-- correct --> <p>foo = <% scalar $m->comp( '.foo' ) %></p>
* this usage is like calling a function that prints data to STDOUT, and our comp does not do this

Convoluted and confusing. One is really better off defining a "shared" array and two separate subs. One that is a true Mason component that only returns data, and the other a true Mason component that only SPITS OUT data:

<%def .get_foo> <%init> my @array = qw(foo bar baz); return @array; </%init> </%def> <%def .display_foo> <% join( '', map "$_<br/>", $m->comp( '.get_foo' ) ) %> </%def> <!-- correct --> <ol> %for ($m->comp( '.get_foo' ) ) { <li><% $_ %></li> %} </ol> <!-- correct --> <& .display_foo &>

I hope this adds some useful points to your excellent meditation.

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)