Perl将参数传递给子例程

Perl将参数传递给子例程

本文介绍了Perl将参数传递给子例程不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将参数传递给perl子例程,并且由于子例程中的任何原因,参数都将变为空.

I'm trying to pass parameters to a perl subroutine and for whatever reason inside the subroutine the parameters are coming out empty.

...
...
...
print "Passing arguments $a, $b, $c, $d \n";
beforeEnd($a, %b, $c, $d);

sub beforeEnd() {
    my ($a, %b, $c, $d) = @_;
    print "a is $a, b is $b, c is $c, d is $d \n";
}

print语句的输出使我知道出了点问题.奇怪的部分?前两个参数正确传递.

The output of the print statements give me an idea that something is wrong. The weird part? The first 2 parameters are passing properly.

> Passing arguments 1, (1,2,3), 2, 3
> a is 1, b is (1,2,3), c is , d is

任何帮助将不胜感激.

推荐答案

因为当您将参数传入或传出子例程时,所有哈希和数组都会被粉碎.

Because when you pass arguments into or out of a subroutine, any hashes and arrays are smashed flat.

您正在分配到%b,它将吞噬所有参数.

You are assigning into %b which will gobble up any arguments.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

sub test1 {
    my ( $first, @rest, $last ) = @_;

    print Dumper \@rest;

    print "First = $first, last = $last, rest = @rest\n";
}

sub test2 {
   my ( $first, $second ) = @_;
   print "@$first ; @$second";
}

test1 ( 1, 2, 3, 4 );
test2 ( [1,2], [ 3,4] );

my @list1 = ( 1,2,3,4 );
my @list2 = ( 5,6,7,8 );

test1 ( @list1, @list2 );
test2 ( \@list1, \@list2 );

如果要保持数组或哈希完整无缺,则需要通过引用或作为最后一个参数传递它们.

If you want to keep arrays or hashes intact, you need to either pass them by reference or as the last argument.

如果在此处打开strictwarnings,也可能会收到警告-这是强烈建议使用的原因之一-因为$b%b不同.您还会收到有关作业数量奇数的警告:

You would also probably get a warning if you turned on strict and warnings here - which is one of the reasons it's strongly recommended - because $b and %b are not the same. You'd also get a warning about an odd number of assignments:

Odd number of elements in hash assignment at line 5.
Use of uninitialized value $b in print

这篇关于Perl将参数传递给子例程不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:17