Adam_ has asked for the wisdom of the Perl Monks concerning the following question:

Today I began Perl so I wrote this little "interactive command line" to play with.

#!/Perl/bin/perl -w while ($command = <STDIN>) { if ($command eq "!1\n"){ $block = ''; open(TESTSCRIPT, 'ts1.pl'); while ($testLine = <TESTSCRIPT>) { $block = $block . $testLine; } $command = $block; } $result = eval $command; print $@; print "\t\t\t== " . $result; print "\n"; }

Sadly, if I perform =~ I cannot read $&, $1, etc. afterwards. Is there a way to do it?

Adam

Replies are listed 'Best First'.
Re: Accessing /$\d/
by grep (Monsignor) on Jul 08, 2003 at 20:28 UTC
    You, unfortunately did not post the relevant code where you performed the regex match.

    So I will assume you wanted the regex at ' if ($command eq "!1\n") ' and you are having the problem with the special regex vars because you are falling out of scope (because you are trying to access the regex vars after)

    $command = $block; }

    What you can do, is while the special regex vars are in scope and that scope is defined by a successful match you can assign $1 to a variable that is defined in the scope you would like to use it in.

    eg. (untested code)

    my $input = <STDIN>; chomp $input; my $script_name = ''; #This is in the main scope if ($input =~ /runme(.+)$/) { $script_name = $1; #$1 is in the scope of #the 'if' block } if ($script_name) { print "Running $script_name\n"; } else { print "Running $input\n"; }

    Please check out Coping with Scoping if this is your problem.

    Please, always post the relevant code, that has been run by you with strict and warnings on.

    grep
    Mynd you, mønk bites Kan be pretti nasti...

      Yup. Seems that the problem was falling out of scope. I assumed $1 variables in Perl are global (like in Ruby) and it seems that they are local.

      Adam