I want to know how can I encapsulate the result(substr($text, 12)
) of the variable $opt
into itself(put the result replacing the expression substr($text, 12)
), but how I 开发者_Go百科can do this?
If needed. Here is my code:
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
I think you want to create an anonymous subroutine that captures the behaviour and references that you want but you don't run until you need it:
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;
my $text;
my $opt = substr($text, 12);
...will give undef errors when you use use strict; use warnings;
-- is this what you intend? You seem to be missing some code. You're using three different variable names: $text
, $opt
, and $command
but do you intend these all to be the same value?
Perhaps this is what you intend, but without more information it's hard to tell:
if ($command =~ /^Hello World Application/i)
{
print substr($command, 12);
}
...but that will always just print Hello World
, so you don't really even need to use a substr
.
EDIT: You still haven't edited your question to give a real example, but you seem to want to be able to modify a variable from inside an if
block and then access it outside the if
block. You can do that by simply ensuring that the variable is declared outside the if
block:
my $variable;
if (something...)
{
$variable = "something else";
}
Please read about "variable scope" at perldoc perlsyn.
精彩评论