in reply to most appropriate return data type
You haven't given enough information to get a specific answer. Why does your function return one number sometimes, more than one other times? What kind of numbers are you generating? How will the return value(s) be used? What are the consequences if some return values are ignored?
I might write a function that returned possible lunch items available for me to eat. If, from the kinds of food in the cupboard, I had more than one possible lunch I might want to return them all. That is, given bread, peanut_butter, jam, bologna, and cheese all in stock, I might return a list of ( 'peanut butter and jelly sandwich', 'meat and cheese sandwich' ). If I call this function in scalar context, I probably will accept any of the available choices, so I should just go ahead and return the list. My scalar caller will get the last available choice.
Or, I might write a function that returns exceptions from some process. The process might succeed or return one or more exception objects, each of which my caller must deal with in some way. I need to use wantarray to be sure my caller has Read The Fine POD; if not, I'm going to die(), which will probably get his attention and encourage him not try to call me in scalar context (thinking there can only be one exception) at all.
Or, my function might return floating-point values from some instrumentation. Normally, only one reading will be returned on any fetch but perhaps I don't want to lose any, so I accumulate readings in some clever way. I should be called in scalar context, for efficiency, since the calls will come fast and frequently. But if I have more than one reading available, I'll return the (cardinal) number of available readings. My caller will notice the integer return and re-call in list context. Here I'll use wantarray to serve the quantity in scalar context and, in list context, to discover that he's taking the backlog off, so I'll clear my buffer.
As usual, the intended purpose of your solution is key to determining the right approach to your code.
|
|---|