Kent Fredric <kentfred...@gmail.com> writes: > On 26 January 2016 at 12:02, Nathan Hilterbrand <noset...@cotse.net> wrote: >> return wantarray() ? ($a, $b) : [$a, $b]; >> >> In a list context, you get back a list.. otherwise you get back a reference >> to a list. Might not be what you want, though. >> >> Works with arrays, too.. >> >> my @anarray = (....) >> return wantarray() ? (@anarray) : [@anarray]; > > > I've found pretty much everywhere you'd want that its simpler to just > return either [@anarray] or just \@anarray > > Returning lists is cute and all, and returning lists only when in list > context is cute ... > > > But in practice I find it mostly painful, because you find yourself > needing to "trick" perl into thinking its in list context from time to > time. > > And even occasional use of > > return (()= function() ) > > Or whatever the right magic is to force the called function into list > context is just more pain than its worth. > > It just seems more practical to always return scalar return values of > some description. > > Now, if you want a more useful application of the comma operator, consider: > > while ( condition ) { > $x = function(), next if $second_condition > }
That's convoluted code to me. If I could read that, I'd read it as while ( $condition ) { $x = function(); next if $second_condition; } > > Which is equivalent to > > while ( condition ) { > $second_condition and $x = function(), next; > } > > Which is similar to > > while( condition ) { > if ( $second_condition ) { > $x = function(); > next; > } > } That is different from the above. If you need it in one line: while ( $condition ) { next unless($second_condition); $x = function(); } > But allows a more compact representation ( which matters if you have a > dozen or so such conditions ), > and avoids adding a lexical scope. You could write while ( $condition ) { $x = function(); next if $second_condition; } instead. I like lexical scopes. But what did you actually want in your first example? This > while( condition ) { > if ( $second_condition ) { > $x = function(); > next; > } > } or that while ( $condition ) { $x = function(); next if $second_condition; } ? > ( Fun fact, replace "$x = > function(), next;" with "do { $x = function(); next }" and watch > deparse turn it back into an "if" statement :) ) > > But you can't use "&&" or "and" in the expression, because > "function()" could return a false value, which would prevent the > 'next' occurring. Perhaps you could also use brackets, like while ( $condition ) { (($second_condition and ($x = function())), 1), next; } for whatever that would do. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/