Order of evaluation of arguments in a subroutine

  • Thread starter Krishna Chaitanya
  • Start date
K

Krishna Chaitanya

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):

====================

#!/usr/bin/perl

sub func { }

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

func($a->(),$b->());

====================

TIA,
Chaitanya
 
K

Keith Thompson

Krishna Chaitanya said:
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 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.
I wrote some sample code like this, and would like to predict its
outcome (if possible):

====================

#!/usr/bin/perl

sub func { }

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

func($a->(),$b->());

====================

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);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top