如何知道perl子程序是否接受参数

时间:2014-10-16 17:31:15

标签: perl parameters subroutine

我是perl的新手,我似乎无法找到有关如何知道子程序是否采用参数的任何信息。

在其他语言中(例如python,java等),很明显,方法/函数通常如下所示:

    def my_func(arg1, arg2):
        # do something

但在perl中,它只是:

    sub my_func {
        my params = @_;
        # do something
    }

但我已经看到了我的params = @_ 甚至不包括在内的示例,但子程序被调用并传递参数。

e.g

    sub my_func {
        my $self = shift;
        my $fieldstr = 'tbl'.$self->db_func.'*,';
        my $sql = "SELECT $fieldstr FROM tbl".$self->db_func.'WHERE'.$self->...;

        my $sth = $self->other_func->my_func($sql) or return undef;
    }

所以我想知道是否有某种指导方针可以知道子程序是否带有参数?

3 个答案:

答案 0 :(得分:4)

请查看my answer to a similar question

Perl是超灵活的,因为子程序可以简单地忽略多余的参数,为缺失的参数提供默认值,或者die如果参数不是完全预期的。< / p>

Perl的作者Larry Wall是一位语言学家,其背后的理由是子程序就像命令式动词一样;就像你可以说“取木头”“从棚子后面取木头,或”从棚子后面取木头拖拉机“,你可以同样地说

fetch($wood)
fetch($wood, $shed)
fetch($wood, $shed, $tractor)

甚至

fetch($wood, {from => 'shed', using => 'tractor'})

由子程序决定是否需要。

应避免使用子程序原型,因为它们具有以不明显的方式改变代码行为的副作用。它们仅用于编写其他语言结构;一个很好的例子是Try::Tiny

答案 1 :(得分:3)

参数在@_中传递,因此您需要查找@_的使用情况。例如,

  • my ($x, $y) = @_;
  • 子中的
  • shiftshift(@_)
  • 相同
  • $_[$i]
  • &f(但不是&f()),与sub log_warn { unshift @_, 'warn'; &log }
  • 一样

作为副作者,你应该尽可能使用它们作为sub的顶部,以使它们显而易见。最后两个通常用作优化或具有引用参数。

答案 2 :(得分:1)

子程序调用的参数包含在数组@_中。

数组操作的两个重要功能是shiftpop。假设你有一个列表(1,2,3,4)。 shift从列表左侧删除一个值并将其返回。

my @list = ( 1, 2, 3, 4 );

my $value = shift @list;

print "$value\n";    # will print "1"
print "@list\n";     # will print "2 3 4"

pop从右侧而不是左侧执行相同的操作:

my @list = ( 1, 2, 3, 4 );

my $value = pop @list;

print "$value\n";    # will print "4"
print "@list\n";     # will print "1 2 3"

在子程序中使用时,popshift默认使用@_数组:

some_function( 'James', 99 );    #these 2 arguments will be passed to the function in "@_"

sub some_function {
    my $name = shift;             #remove 'James' from list @_ and store it in $name
    my $age  = shift;             #remove 99 from list @_ and store it in $age
    print "Your name is $name and your age is $age\n";
}
相关问题