Order of evaluation of arguments in a subroutine

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
In Perl, is the order of evaluating subroutine args L-to-R?

I saw in perlop that a comma operator in a list context evaluates from
L-to-R, and also in perlsub that all args to a subroutine are squashed
into 1 single list......can I deduce from these 2 statements that
order of evaluation of subroutine args is L-to-R as well?

I wrote some sample code like this, and would like to predict its
outcome (if possible):



sub func { }

my $a = sub { print "Hello"; };
my $b = sub { print " world "; };




Re: Order of evaluation of arguments in a subroutine

Quoted text here. Click to load it

I believe so.  "perldoc perlop" says:

    Comma Operator
        Binary "," is the comma operator.  In scalar context
        it evaluates its left argument, throws that value away,
        then evaluates its right argument and returns that value.
        This is just like C’s comma operator.

        In list context, it’s just the list argument separator, and
        inserts both its arguments into the list.  These arguments
        are also evaluated from left to right.

I'm fairly sure that subroutine arguments are evaluated as an ordinary
list, so the second paragraph would apply.

Quoted text here. Click to load it
Consider whether you really need to do this?  I'm not 100% certain
that my conclusion above is correct (though I'll be more confident
if nobody shoots it down in flames in the next couple of days).
And though it's not entirely relevant, there are plenty of other
languages in which the order of evaluation of subroutine arguments
is unspecified.

Even if the language guarantees left-to-right evaluation, I suggest
that your code would likely be clearer if it didn't depend on
this guarantee.

my $first = $a->();
my $second = $b->();
func($first, $second);

Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

Site Timeline