views:

78

answers:

2

Hello,
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 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
+4  A: 
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.

Ether
I'm using strict and warnings, but that is only a snippet. My code have 452 lines.
Nathan Campos
The snippet you have provided doesn't really make sense, so you will need to add clarification.
Ether
This is a test, but how I can that into the variable and print it outside the if?
Nathan Campos
I still don't understand the question :)
Ivan Nevostruev
+4  A: 

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;
brian d foy
A cogent answer to a very unclear question
glenn jackman
Brian. You're the guy! I've already imported all your books since two days **;)**
Nathan Campos