调用Perl哈希函数

时间:2019-06-17 15:56:40

标签: perl

如何从哈希值调用函数?

%hash = { "1" => \&some_function } ; # this function has one parameter
sub some_function {
  my $arg = $_[0];
  return $arg;
}
$hash{"1"}->($arg); <-- tried this but doesn't work.

2 个答案:

答案 0 :(得分:6)

upstream gitlab { server 172.17.42.1:10080 fail_timeout=0; } # let gitlab deal with the redirection server { listen 80; server_name gitlab.mydomain.com; server_tokens off; root /dev/null; # Increase this if you want to upload larger attachments client_max_body_size 20m; # individual nginx logs for this vhost access_log /var/log/nginx/gitlab_access.log; error_log /var/log/nginx/gitlab_error.log; location / { proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Frame-Options SAMEORIGIN; proxy_pass http://gitlab; } } server { listen 443 ssl spdy; server_name gitlab.mydomain.com; server_tokens off; root /dev/null; ## Increase this if you want to upload larger attachments client_max_body_size 20m; # listen [::]:443 ssl ipv6only=on; # managed by Certbot #listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/ghware.de/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/ghware.de/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot ssl on; ## Individual nginx logs for this vhost access_log /var/log/nginx/gitlab_ssl_access.log; error_log /var/log/nginx/gitlab_ssl_error.log; location / { ## If you use https make sure you disable gzip compression ## to be safe against BREACH attack. gzip off; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Frame-Options SAMEORIGIN; proxy_pass http://gitlab; } }是一个哈希。 %hash是一个哈希引用。 您需要以下变体之一:

{ "1" => \&some_function }

$hash = { "1" => \&some_function };
$hash->{"1"}->($arg);

有关详细信息,请参见perldataperlref

答案 1 :(得分:4)

要声明哈希,请使用圆括号。花括号用于哈希引用/匿名哈希。

%hash = ( 1 => \&some_function );
sub some_function {
    my $arg = $_[0];
    return $arg
}
$hash{1}($arg);