in reply to Use of wantarray Considered Harmful
<%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:
* this usage is like calling a function that prints data to STDOUT, and our comp does not do this<!-- correct --> <p>foo = <% scalar $m->comp( '.foo' ) %></p>
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)
|
---|