Passing arrays to functions in Perl

前端 未结 3 1268
北荒
北荒 2021-02-19 04:03

I think I have misunderstood some aspects of argument passing to functions in Perl. What\'s the difference between func(\\@array) and func(@array)?

3条回答
  •  鱼传尺愫
    2021-02-19 04:46

    It's impossible to pass arrays to subs. Subs take a list of scalars for argument. (And that's the only thing they can return too.)

    You can pass a reference to an array:

    func(\@array)
    

    You can pass the elements of an array:

    func(@array)
    

    When should we use which?

    If you want to pass more than just the elements of the array (e.g. pass $x, $y and @a), it can become tricky unless you pass a reference.

    If you're going to process lists (e.g. sum mysub grep { ... } ...), you might not want to pass a reference.

    If you want to modify the array (as opposed to just modifying the existing elements of the array), you need to pass a reference.

    It can be more efficient to pass a reference for long arrays, since creating and putting one reference on the stack is faster than creating an alias for each element of a large array. This will rarely be an issue, though.

    It's usually decided by one of the first two of the above. Beyond that, it's mostly a question of personal preference.


    Also, how do I imitate pass-by-value in Perl?
    sub foo {
       my ($x) = @_;   # Changing $x doesn't change the argument.
       ...
    }
    
    sub foo {
       my @a = @_;   # Changing @a or its contents
       ...           #    doesn't change the arguments.
    }
    

提交回复
热议问题