tford has asked for the wisdom of the Perl Monks concerning the following question:
This code produces the following output.sub argout { my $temp = {'type'=>'ARG', 'value'=>$buffer}; $buffer = ''; push(@output,$temp); } sub otherout { my $c = shift; my $temp = {'type'=>'OTHER', 'value'=>$c}; push(@output,$temp); } %states = ( 'start'=>{'s'=>{'nextstate'=>'var1.1'}}, 'var1.1'=>{'i'=>{'nextstate'=>'var1.2'}}, 'var1.2'=>{'s'=>{'action'=>'argout', 'nextstate'=>'var1.1'}, 'eof'=>{'action'=>'argout'}} ); sub lex { my $inputstring = shift; my @input = split('',$inputstring); my @output = (); $buffer = ''; my $s = 'start'; foreach my $c (@input,'eof') { if( my $t = $states{$s}->{$c} ) { eval( $t->{'action'} ); $s = $t->{'nextstate'}; } else { otherout($c); return 0; } $buffer = $buffer.$c; } return 1; } if( lex('sisisi') ) { print("success!\n"); } else {print("failure...")} foreach my $tok (@output) { print("$tok->{'type'},$tok->{'value'}\n"); }
It seems to rely on the $buffer being a sort of "global" variable (global vars are bad right?), so that the argout function can access it. Now if I add a 'my' keyword in front of the $buffer declaration (inside the lex subroutine) then the output is the following.success! ARG,si ARG,si ARG,si
Presumably this is because the $buffer variable is no longer accessible from the 'argout' subroutine. Why is the @output variable accessible from the 'argout' subroutine even though it is declared local to 'lex'?success! ARG, ARG, ARG,
Knowing this would be one thing, but what I really want is that the $buffer, the @input, the @output, and possibly even the $c would be data inside of a "Dfa" object, and all of those other methods could just access those variables whenever they wanted. The reason I haven't done this yet is that the only way I know how to make objects in Perl is to make sort of a "special hash" and bless it with functions that have intimate access to it. I didn't want to do this because I didn't want to have to use constructs like $self->{'buffer'} everytime I wanted to use the buffer variable.
I feel like I'm still stuck in a sort of "Java Mode" of thinking right now...Is there a better, "Perler" way of doing all this?
Any help will be greatly appreciated,
~Terry
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Help with Variable Scope
by pc88mxer (Vicar) on Apr 30, 2008 at 04:47 UTC | |
by tford (Beadle) on May 04, 2008 at 21:17 UTC | |
Re: Help with Variable Scope
by Fletch (Bishop) on Apr 30, 2008 at 04:05 UTC |