Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

Expression Evaluation Context

This section describes expression evaluation contexts: scalar context and list context. Operations and function may behave differently in different context. A list value in a scalar context is converted by taking the last value.

Depending on where it is used, an expression will be evaluated under two different context, Scalar Context and List Context.

1. Scalar Context - When an expression is used as an argument of an operation that requires a scalar value, the expression will be evaluated under a scalar context. For example, 9.99 * EXPR requires EXPR to be evaluated in a scalar context.

2. List Context - When an expression is used as an argument of an operation that requires a list value, the expression will be evaluated under a list context. For example, sort(EXPR) requires EXPR to be evaluated in a list context.

Expressions behave differently in different contexts following these rules:

  • An expression in a scalar context will be evaluated to a scalar value.
  • An expression in a list context will be evaluated to a list value.
  • Some operators automatically return different values in different contexts. For example: <IN> will read and return only one line as a string in a scalar context. <IN> will read and return all lines as a list of strings in a list context.
  • Some functions automatically returns different values in different contexts. For example: sort(LIST) will sort all elements of the input list and return them as a list in a list context. sort(LIST) will return the 'undef' value in a scalar context.
  • If the expression returns scalar value in a list context, Perl will convert it into a list value with one element - the returned scalar value.
  • If the expression returns list value in a scalar context, Perl will convert it into a scalar value by take the last element of the returned list value.

Here is a Perl tutorial script on how expressions are evaluated in a scalar or list context:

#- ExpressionContext.pl
#- Copyright (c) 1995 by Dr. Herong Yang, http://www.herongyang.com/
#

   @links = ("herongyang.com", "perl.org", "cpan.org");

   $string = join(', ',sort(@links));   # sort() in a list context
   print($string, "\n");

   $string = "My bookmarks: ".sort(@links);
                                        # sort() in a scalar context
   print($string, "\n");

   $interest = 39.99;
   $capital = 1234.56;
   @rates = $interest/$capital;         # converting scalar to list
   print(@rates, "\n");

   $interest = 100*(0.02, 0.05, 0.03);  # converting list to scalar   
   print($interest, "\n");

Here is the output of the tutorial script:

cpan.org, herongyang.com, perl.org
My bookmarks:
0.0323921073094868
3

Sections in This Chapter

What Is an Expression?

Expression Evaluation Context

Simple Statements and Modifiers

Dr. Herong Yang, updated in 2008
Expression Evaluation Context