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

前端 未结 3 1323
自闭症患者
自闭症患者 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:53

    This simply means that a data-type will be evaluated based on the mode of the operation. For example, an assignment to a scalar means the right-side will be evaluated as a scalar.

    I think the best means of understanding context is learning about wantarray. So imagine that = is a subroutine that implements wantarray:

    sub = {
      return if ( ! defined wantarray ); # void: just return (doesn't make sense for =)
      return @_ if ( wantarray ); # list: return the array
      return $#_ + 1; # scalar: return the count of the @_
    }
    

    The examples in this post work as if the above subroutine is called by passing the right-side as the parameter.

    As for parallels in other languages, yes, I still maintain that virtually every language supports something similar. Polymorphism is similar in all OO languages. Another example, Java converts objects to String in certain contexts. And every untyped scripting language i've used has similar concepts.

提交回复
热议问题