下面是我正在处理的更大代码片段的代码片段,当我尝试在函数@ $ instanceObjectEnrichment [0]
中引用数组时,我会不断收到此错误my @providerCloudEnrichment=("Core","Gen-i WAN Services","Physical Provider Connectivity","TEMPLATE");
createAndEnrichInstance($parentClass,$session,$object,@providerCloudEnrichment);
sub createAndEnrichInstance {
my ($creationClassName,$session,$instanceObjectString,$instanceObjectEnrichment)=@_;
if(!($session->instanceExists($instanceObjectString))){
$session->create($instanceObjectString);
}
my $instanceObject=$session->object($instanceObjectString);
print("i am here ".@$instanceObjectEnrichment[0]."\n");
if($creationClassName eq 'ProviderCloud'){
$instanceObject->put(Model =>"@$instanceObjectEnrichment[0]",Vendor =>"@$instanceObjectEnrichment[1]",Description =>"@$instanceObjectEnrichment[2]",Certification => "@$instanceObjectEnrichment[3]");
}
elsif($creationClassName eq 'Interface'){
$instanceObject->put(Model =>@$instanceObjectEnrichment[0],Vendor =>@$instanceObjectEnrichment[1],Description=>@$instanceObjectEnrichment[2],DisplayName=>@$instanceObjectEnrichment[3],DeviceID=>@$instanceObjectEnrichment[4]);
}
else {
print ("Incorrect Class");
}
}
ERROR
Can't use string ("Core") as an ARRAY ref while "strict refs" in use at createUserDefinedConnections.pl line 149, <$udf> line 326.
答案 0 :(得分:4)
您应该将其作为数组引用传递:
createAndEnrichInstance($parentClass,$session,$object,\@providerCloudEnrichment);
此
createAndEnrichInstance($parentClass,$session,$object,@providerCloudEnrichment);
相当于:
createAndEnrichInstance($parentClass,$session,$object,"Core","Gen-i WAN Services","Physical Provider Connectivity","TEMPLATE")
此外,由于它是一个数组引用,您可以更改
@$instanceObjectEnrichment[0]
是:
$instanceObjectEnrichment->[0]
答案 1 :(得分:0)
将引用传递给数组,或创建无名数组并传递对它的引用。
请参阅live demo。
#!/usr/bin/env perl
use strict;
use warnings;
print "First approach: Pass a reference to the array",
" using the backslash operator:\n";
my @words = ("Practical", "Extraction and", "Reporting", "Language");
print_words(\@words);
print "\nSecond approach: Pass a reference to an anonymous array:\n";
my $words_ref = ["Practical", "Extraction and", "Reporting", "Language"];
print_words($words_ref);
sub print_words {
my ($words_ref) = @_;
for (0 .. $#$words_ref) {
print "$_. ", $words_ref->[$_], "\n";
}
}
预期输出:
First approach: Pass a reference to the array using the backslash operator:
0. Practical
1. Extraction and
2. Reporting
3. Language
Second approach: Pass a reference to an anonymous array:
0. Practical
1. Extraction and
2. Reporting
3. Language