What is the difference between the scalar and list contexts in Perl?

前端 未结 3 1343
自闭症患者
自闭症患者 2021-01-06 00:12

What is the difference between the scalar and list contexts in Perl and does this have any parallel in other languages such as Java or Javascript?

3条回答
  •  时光取名叫无心
    2021-01-06 00:37

    Scalar context is what you get when you're looking for a single value. List context is what you get when you're looking for multiple values. One of the most common places to see the distinction is when working with arrays:

    @x = @array;  # copy an array
    $x = @array;  # get the number of elements in an array
    

    Other operators and functions are context sensitive as well:

    $x   = 'abc' =~ /(\w+)/;  # $x = 1
    ($x) = 'abc' =~ /(\w+)/;  # $x = 'abc'
    @x   = localtime();       # (seconds, minutes, hours...)
    $x   = localtime();       # 'Thu Dec 18 10:02:17 2008'
    

    How an operator (or function) behaves in a given context is up to the operator. There are no general rules for how things are supposed to behave.

    You can make your own subroutines context sensitive by using the wantarray function to determine the calling context. You can force an expression to be evaluated in scalar context by using the scalar keyword.

    In addition to scalar and list contexts you'll also see "void" (no return value expected) and "boolean" (a true/false value expected) contexts mentioned in the documentation.

提交回复
热议问题