The behavior in scalar context is undefined.

I was just reading the docs of Email::Address when I encountered this warning. I know this is not the only place where the behavior in scalar context is undefined, but I wonder. Wouldn't it be better to throw an exception or at least print a warning when a function such as the parse method of Email::Address is called in scalar (or void) context?


That would eliminate the incorrect usage faster probably also reducing the questions asked by users. It will also make it easier to add a different functionality later on, without surprising the people who used the method incorrectly.

1 Comment

One reason not to check the context and throw an exception would be that it the check would very slightly slow down each call of the sub. If it's a sub that could be called millions of times in a single run of a process, it may make sense to exclude such a check as a minor optimization.

Another reason would be that if your sub has side effects, your caller might simply not care about the return value of the sub - they might be calling your sub exclusively to take advantage of the side effects. The side effects might include IO, changes to global variables, or throwing exceptions.

For example, say I had a function which parsed an e-mail address (I wonder why I came up with that as an example), and returned a two element list of the user name and host name, but threw an exception if the e-mail address was invalid. Perhaps you don't care about the user name or host name; you just care that all e-mail addresses handled by your program are valid. Then you might call my function in a void context, and be happy with the returned list getting discarded. Why should my function insist you call it in list context?

Leave a comment

About Gábor Szabó - גאבור סבו

user-pic I blog about Perl.