Creating arrays dynamically in Perl

后端 未结 4 1723
旧巷少年郎
旧巷少年郎 2020-12-07 02:04

I want to create arrays dynamically based on the user input. For example, if the user gives input as 3 then three arrays should be created with the name @message1

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 02:37

    In compiled languages, variables don't have a name. The name you see in the code is a unique identifier associated with some numerical offset. In an identifier like message_2 the '2' only serves to make it a unique identifier. Anybody can tell that you could make your three variables: message_125, message_216, and message_343. As long as you can tell what you should put into what, they work just as well as message_1...

    The "name" of the variable is only for you keeping them straight while you're writing the code.

    Dynamic languages add capability by not purging the symbol table(s). But a symbol table is simply an association of a name with a value. Because Perl offers you lists and hashes so cheaply, there is no need to use the programming/logistical method of keeping track of variables to allow a flexible runtime access.

    Chances are that if you see yourself naming lists @message1, @message2, ... -- where the items differ only by their reference order, that these names are just as good: $message[1], $message[2], ....

    In addition, since symbol tables are usually mapping from name-to-offset (either on the stack or in the heap), it's really not a whole lot more than a key-value pair you find in a hash. So hashes work just as good for looking up more distinct names.

    $h{messages} = [];
    $h{replies}  = [];
    

    I mean really if you wanted to, you could store everything that you put into a lexical variable into a single hash for the scope, if you didn't mind writing: $h{variable_name} for everything. But you wouldn't get the benefit of Perl's implicit scope management, and across languages, programmers have preferred implicit scope management.

    Perl allows symbolic manipulation, but over the years the dynamic languages have found that a mixed blessing. But in Perl you have both "perspectives", to give them a name. Because you can determine what code in a compiled language is likely to do better than a dynamic language, it has been determined more error free to use a "compiled perspective" for more things: So as you can see with the availability of offset-management and lookup compiled behavior given to you in core Perl, there is no reason to mess with the symbol table, if you don't have to.

    Creating an array dynamically, is as simple as: []. Assigning it to a spot in memory, when we don't know how many we want to store, is as easy as:

    push @message, [];
    

    And creating a list of lists all at once is as easy as:

    @message = map { [] } 1..$num_lists;
    

    for some specified value in $num_lists.

提交回复
热议问题