Perl将常量传递给子程序

时间:2012-08-25 22:43:00

标签: perl parameters constants subroutine

我有以下内容:

#! /usr/bin/perl

use strict;

# Declare some meaningful named constants
use constant {FOO => 2,
              BAR => 3,
              BAM => 4};

# Define paths between the named entities
my %PATHS = (FOO => {BAR => "Foo->Bar",
                     BAM => "Foo->Bam"},
             BAR => {FOO => "Bar->Foo",
                     BAM => "Bar->Bam"},
             BAM => {FOO => "Bam->Foo",
                     BAR => "Bam->Bar"});

# Printing out PATHS map does more or less what I expect:
foreach my $src (sort keys %PATHS) {
  foreach my $dst (sort keys %{ $PATHS{$src} } ) {
    print "$src:$dst\t$PATHS{$src}{$dst}\n";
  }
}

# I can't use the constants as parameters
sub findPath($$) {
  my $src = shift;
  my $dst = shift;

  print "src:$src\ndst:$dst\n";
  my $path = $PATHS{$src}{$dst};
  print defined $path ? "path=$path\n" : "UNDEFINED\n";
}

findPath(FOO, BAR);

似乎我的常量被视为裸字,并且在HoH PATHS的声明中添加了隐式引号。有没有一种简单的方法来定义这样的映射,其中符号键可以在函数调用中使用?

2 个答案:

答案 0 :(得分:2)

=>运算符执行两项操作:

  1. 引用左边的
  2. 就像一个逗号
  3. 如果您只想要#2,请使用逗号。

答案 1 :(得分:0)

Perl常量实际上只是不带参数并返回固定值的子程序。

这意味着您可以将&前缀添加到强制它们进行插值:

my %PATHS = (&FOO => {&BAR => "Foo->Bar",
                      &BAM => "Foo->Bam"},
             &BAR => {&FOO => "Bar->Foo",
                      &BAM => "Bar->Bam"},
             &BAM => {&FOO => "Bam->Foo",
                      &BAR => "Bam->Bar"});

并保持显示key =>的漂亮=>语法价值关系。

您还可以使用始终有效的旧@{[...]}技巧:

print "The value of constant FOO is '@{[FOO]}'\n";

用眼睛比用这个更容易解析:

print "The value of constant FOO is '" . FOO . "'\n";