0

我想知道如何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
4

2 回答 2

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

...当你使用时会给出 undef 错误use strict; use warnings;-- 这是你想要的吗?您似乎缺少一些代码。您正在使用三个不同的变量名称:$text, $opt,$command但是您是否希望这些都具有相同的值?

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

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

...但那总是只是 print Hello World,所以你甚至不需要使用substr.

编辑:你仍然没有编辑你的问题来给出一个真实的例子,但你似乎希望能够从一个if块内修改一个变量,然后在if块外访问它。您可以通过简单地确保在if块外声明变量来做到这一点:

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

请在perldoc perlsyn阅读“变量范围” 。

于 2009-12-09T17:02:23.127 回答
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;
于 2009-12-09T20:10:52.133 回答