如何创建一个接受数组*或*可变数量标量的子程序?

时间:2022-12-08 23:17:49

I'm looking to make a subroutine mysub which should behave such that the following two calls are effectively the same.

我正在寻找一个子程序mysub,它应该表现为以下两个调用实际上是相同的。

mysub(["values", "in", "a", "list"]);
mysub("Passing", "scalar", "values");

What is the proper syntax to make this happen?

实现这一目标的正确语法是什么?

1 个解决方案

#1


18  

Check if @_ contains a single array reference.

检查@_是否包含单个数组引用。

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        # Single array ref
    } else {
        # A list
    }
}

The if clause checks that only one argument was passed and that the argument is an array reference using ref. To make sure that the cases are the same:

if子句检查只传递了一个参数,并且参数是使用ref的数组引用。为了确保案例相同:

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        @_ = @{ $_[0] };
    }
    # Rest of the code
}

#1


18  

Check if @_ contains a single array reference.

检查@_是否包含单个数组引用。

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        # Single array ref
    } else {
        # A list
    }
}

The if clause checks that only one argument was passed and that the argument is an array reference using ref. To make sure that the cases are the same:

if子句检查只传递了一个参数,并且参数是使用ref的数组引用。为了确保案例相同:

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        @_ = @{ $_[0] };
    }
    # Rest of the code
}