Perl compilation woes

2019-08-16 20:30发布

I'm having some troble compiling this method:

#changes the names of the associations for $agentConf
#where the key value pairs in %associationsToChangeDict are the old and new values respectively
sub UpdateConfObjectAssociations{
    my($agentConf, %associationsToChangeDict) = @_;

    foreach my $association ($agentConf->GetAssociations()) {
        if ( grep {$_ eq $association->Name()} keys %associationsToChangeDict) {
            my $newValue = %associationsToChangeDict{$association->Name()};
            $association->Value($newValue);
        } 
    }   
}

This is the error message:

syntax error at D:\Install\AutoDeployScripts\scripts\Perl/.\AI\SiteMinderHelper
.pm line 75, near "%associationsToChangeDict{"
syntax error at D:\Install\AutoDeployScripts\scripts\Perl/.\AI\SiteMinderHelper
.pm line 79, near "}"

Can anyone see where the problem is?

1条回答
beautiful°
2楼-- · 2019-08-16 21:05

Yes, you can get a slice (i.e. multiple values) from a hash like this:

my @slice = @hash{ @select_keys };

And you can get a single value from a hash like this:

my $value = $hash{ $key };

But you cannot address a hash with a beginning '%' sigil. It's meaningless short of Perl 6 (where sigils won't change according to number).

Because you want a single item out of the hash, your assignment should be:

my $newValue = $associationsToChangeDict{ $association->Name() };

There are three contexts in Perl, void, scalar, and list. A sigil is more an indicator of context than part of the variable name. We see a void context when nobody is expecting a result back from an expression. This context only occurs in sub-s, when the programmer just wants something done, and does not care if a value is returned.

That leaves only scalar and list when talking about variables. These kind of work like singular and plural forms in a language. Since Larry Wall was influenced by natural languages in designing Perl, these parallels are, well, natural. But there is no "hash context". Of course to complicate matters just slightly, something evaluated to be a list when wrapped in a scalar context, has a contextual meaning as well, it just evaluates to the magnitude of the resulting list.

You would not likely do this (but it has a meaning):

my $count = @list[1..4];

But you could do this:

my $count = ( grep { $_ % 2 == 0 } @list[ @subscripts ] );

It would do all that list context evaluation inside the parens, to evaluate to the single value of the total of items in the list. (Although grep is probably intelligent enough to count successes, instead of forming a new list since context is propagated in Perl.)

查看更多
登录 后发表回答