gpt4 book ai didi

perl - 如何将数组和散列数据类型传递给 perl 中的子例程参数?

转载 作者:行者123 更新时间:2023-12-04 13:07:18 27 4
gpt4 key购买 nike

我在 perl 子例程定义中声明数组类型参数时遇到编译错误。
我的完整代码如下:

use Data::Dumper;
use Win32;
use Win32::Service;
use strict;
use warnings;
my @Services = qw(NNMAction RpcEptMapper smstsmgr SNMPTRAP);
my $server = 'nnmi.hclt.corp.hcl.in';
ServiceStatus($server , @Services);

sub ServiceStatus ($serverName,@serverServices)
{ my %statcodeHash = ( '1' => 'stopped',
'2' => 'start pending',
'3' => 'stop pending',
'4' => 'running',
'5' => 'continue pending',
'6' => 'pause pending',
'7' => 'paused' );

foreach my $serv (@serverServices)
{ my %status;
my $ret = Win32::Service::GetStatus($serverName , $serv , \%status);
if ($ret)
{ print "success \t$statcodeHash{$status{CurrentState}} \t$serv\n";
}
else
{ print Win32::FormatMessage(Win32::GetLastError()), "\n";
}
}
}

编译错误
>perl -w perl_RemoteServiceStatus.pl
Prototype after '@' for main::ServiceStatus : $serverName,@serverServices at per
l_RemoteServiceStatus.pl line 21.
Illegal character in prototype for main::ServiceStatus : $serverName,@serverServ
ices at perl_RemoteServiceStatus.pl line 21.
main::ServiceStatus() called too early to check prototype at perl_RemoteServiceS
tatus.pl line 16.
Global symbol "@serverServices" requires explicit package name at perl_RemoteSer
viceStatus.pl line 31.
Global symbol "$serverName" requires explicit package name at perl_RemoteService
Status.pl line 33.
Execution of perl_RemoteServiceStatus.pl aborted due to compilation errors.

请帮我调试这些代码。我相信这对某些人来说是小菜一碟。

最佳答案

真的很简单:不要使用prototypes如果你不知道它们是如何工作的。要让您的代码运行,请将子程序声明从:

sub ServiceStatus ($serverName,@serverServices)
{ #...

到:
sub ServiceStatus {
my ($serverName, @serverServices) = @_;

编辑:如果您需要将多个数组/散列传递给子例程,或者应该在其他值之前传入一个数组/散列,则必须通过引用传递它:
sub complex_params {
my ($array1, $scalar, $hash, $array2) = @_;

# dereference
my @a1 = @$array1;
my @a2 = @$array2;
my %h = %$hash;

#...
}

# reference
complex_params(\@some_array, $some_scalar, \%some_hash, \@other_array);

关于perl - 如何将数组和散列数据类型传递给 perl 中的子例程参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13969145/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com