Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Re: Re: Context aware functions - best practices?

by ihb (Deacon)
on Jan 15, 2003 at 20:05 UTC ( [id://227214]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Context aware functions - best practices?
in thread Context aware functions - best practices?

An argument against this is that the user expects a list to be returned, not an array.

While I understand your argument I believe that it is the user that errors. The error lies in his expectation. If a subroutine is documented to return a list it's also implicitly documented only for list context. When calling such a subroutine in scalar context you can't expect anything to happen--even less something sane to happen; there are no lists in scalar context. Take sort() for instance. That's obviously a list-context function, and you don't expect it to do anything useful at all in scalar context. Aristotle's problem is not as clear, but my point is still that if a subroutine is documented to return a list it's only documented for list context. Every other behaviour is undefined.

But you also hit the nail when saying that we should code so that our routines get intuitive. So yes, I do partly agree with your argument.

In terms of intuition, most people intuitively expect the following two expressions to be equivalent:
my($x) = foo(...);
And:
my $x = foo(...);


Yes, but this intuition is quickly counter-prooved by the numerous bugs that will come to any programmer expecting this. This is probably the first context bug that Perl programmers will meet. And usually, when past the newbie state, they don't get that wrong anymore. I too want to write easy-to-use code, but I expect a certain level of Perl understanding of my users, and list vs. scalar assignment is a basic thing in Perl.

I'm undecided...

ihb

Replies are listed 'Best First'.
Re: Re: Re: Re: Context aware functions - best practices?
by sauoq (Abbot) on Jan 15, 2003 at 22:56 UTC
    That's obviously a list-context function, and you don't expect it to do anything useful at all in scalar context.

    You make a good point here. Some functions just shouldn't be expected to do anything useful in scalar context. A nice idiom for writing such functions is to start them with wantarray or return undef.

    -sauoq
    "My two cents aren't worth a dime.";
    
      Or maybe just return unless wantarray; because return is smart enough to provide undef by itself in scalar context. :)

      Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://227214]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-18 10:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found