Problems? Is your data what you think it is? | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Expectations should be defined by the language, not the programmer. Therefore, I think we should standardize on... well, nothing. Because Perl doesn't. I do, however, believe there is a best practice: unless you have a very good reason, it is best to sidestep the issue entirely and let Perl provide behavior that is already familiar to the programmer. It is easy to imagine a function where it makes the most sense to return a reference to an array in scalar context. Likewise, it is easy to imagine one where it makes the most sense to return a formatted string. Neither would make sense as a default though. They are special cases. In fact, the only time you should be mucking around with the return value in different contexts is when you have a special case. (And it just so happens that many, if not most, of Perl's builtins are sensibly treated as special cases.) The right "default" behavior, in my opinion, is to return @ret; and let the programmer using your function sort it out. Document that your function returns an array and be done with it. Perl does a fine job of defining expectations for arrays, and your function can rely on those... That's about as consistent as it gets in Perl. It'll serve you well too, should you need to globally replace an array with a function call or vice-versa. I think that returning a list literal (such as you create with the slice @ret[0 .. $#ret] in your example) is sorta-semi-okay as an alternative, but probably not nearly as useful. It also isn't very common practice and should probably be much more carefully documented when used. Still, I suppose Perl provides the right expectations insofar as $x = qw( a b c ); and sub f { qw(a b c) }; $x = f(); both set $x equal to 'c'. Out of all of your examples, the one that makes me cringe is your "something completely different" example. Why go to the trouble ensuring my $i = foo(); is equivalent to my ($i) = foo(); when most perl programmers have already gone to the trouble to learn that they probably aren't? It hardly seems worth the obfuscation. I expect most, if they ran across that function, would spend much longer trying to figure out exactly why you did it that way than they ever would working out a bug caused by calling it in scalar context. I include myself in that. -sauoq "My two cents aren't worth a dime."; In reply to Re: What should be returned in scalar context? (best practice)
by sauoq
|
|