在变量中封装内容

时间:2009-12-09 16:57:35

标签: perl variables encapsulation

我想知道如何将变量substr($text, 12)的结果($opt)封装到自身中(将结果替换为表达式substr($text, 12)),但我怎么能这样做?

如果需要的话。这是我的代码:

my $text;
my $opt = substr($text, 12);
if ($command =~ /^Hello World Application/i) {
    print "$opt\n";
}
# More code....
print # Here I want to print the result of 'substr($text, 12)' in the if

2 个答案:

答案 0 :(得分:4)

my $text;
my $opt = substr($text, 12);

...当你使用use strict; use warnings;时会给出undef错误 - 这是你想要的吗?你似乎错过了一些代码。您使用了三个不同的变量名称:$text$opt$command,但您是否打算将这些变量设为相同的值?

也许这就是你想要的,但没有更多的信息,很难说:

if ($command =~ /^Hello World Application/i)
{
    print substr($command, 12);
}

...但总是只打印Hello World,所以您甚至不需要使用substr

编辑:您仍未编辑问题以提供真实示例,但您似乎希望能够从if块内修改变量然后访问它在if区块之外。您可以通过简单地确保变量在if块之外声明来实现:

my $variable;
if (something...)
{
    $variable = "something else";
}

请在perldoc perlsyn了解“变量范围”。

答案 1 :(得分:4)

我认为你想创建一个匿名子程序来捕获你想要的行为和引用,但是在你需要它之​​前就不会运行:

my $text;  # not yet initialized
my $substr = sub { substr( $text, 12 ) };  # doesn't run yet

... # lots of code, initializing $text eventually

my $string = $substr->(); # now get the substring;