Why is there so much “magic” in Perl?

前端 未结 6 1446
名媛妹妹
名媛妹妹 2021-02-02 15:18

Looking through the perlsub and perlop manpages I\'ve noticed that there are many references to \"magic\" and \"magical\" there (just search any of them for \"magic\"). I wonder

6条回答
  •  甜味超标
    2021-02-02 15:52

    Magic, in Perl parlance is simply the word given to attributes applied to variables / functions that allow an extension of their functionality. Some of this functionality is available directly from Perl, and some requires the use of the C api.

    A perfect example of magic is the tie interface which allows you to define your own implementation of a variable. Every operation that can be done to a variable (fetching or storing a value for instance) is exposed for reimplementation, allowing for elegant and logical syntactic constructs like a hash with values stored on disk, which are transparently loaded and saved behind the scenes.

    Magic can also refer to the special ways that certain builtins can behave, such as how the first argument to map or grep can either be a block or a bare expression:

    my @squares = map {$_**2} 1 .. 10;
    my @roots   = map sqrt, 1 .. 10;
    

    which is not a behavior available to user defined subroutines.

    Many other features of Perl, such as operator overloading or variables that can return different values when used with numeric or string operators are implemented with magic. Context could be seen as magic as well.

    In a nutshell, magic is any time that a Perl construct behaves differently than a naive interpretation would suggest, an exception to the rule. Magic is of course very powerful, and should not be wielded without great care. Magic Johnson is of course involved in the execution of all magic (see FM's answer), but that is beyond the scope of this explaination.

提交回复
热议问题