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、 の3 つの異なる変数名を使用して$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で「変数スコープ」について読んでください。

于 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 に答える